SubbaReddy M wrote:
> RE: Sorting hash by valueHello Gurus,
>
> I want little bit more help on the same track, so please give me hint on
> this:
> " How to assign the keyset of the list variable(hash), on which done the
> sorting by value? "
>
> How could I sort the list variable?
> I would like to asign the returned keys set of the sorted by value in the
> list variable. Is it possible?
>
> i.e.,
> first I want to sort the %hash by value and then asign the keys to a
> varialbe.
> => for example
> my @keySet = keys %hash sort( values %hash);
>
> here is a code snippet to do the trick, but it is working fine, if the
> values of the %hash are integers, but not if values are strings.
>
> %hash = (
> "key1" => "1",
> "key2" => "3",
> "key3" => "2"
> );
>
> sub vsrt
> {
> $hash{$a} <=> $hash{$b};
> }
>
> foreach $k (sort vsrt keys %hash)
> {
> $keySet[$ki] = $hash{$k}; $ki++;
> }
>
> # it's not working for %hash1
> %hash1 = (
> "key1" => "value1",
> "key2" => "value3",
> "key3" => "value2"
> );
>
> sub vsrt
> {
> $hash1{$a} <=> $hash1{$b};
> }
>
> foreach $k (sort vsrt keys %hash1)
> {
> $keySet[$ki] = $hash1{$k}; $ki++;
> }
>
>
> Please, how to get it done.
cmp is used in place of <=> for non-numeric sorts:
use strict;
my @keySet = ();
my %hash = (
"key1" => "1",
"key2" => "3",
"key3" => "2"
);
my $ki = 0;
foreach my $k (sort { $hash{$a} <=> $hash{$b} } keys %hash) {
$keySet[$ki] = $hash{$k}; $ki++;
}
print "@keySet\n";
# it's not working for %hash1
@keySet = ();
my %hash1 = (
"key1" => "value1",
"key2" => "value3",
"key3" => "value2"
);
$ki = 0;
foreach my $k (sort { $hash1{$a} cmp $hash1{$b} } keys %hash1) {
$keySet[$ki] = $hash1{$k}; $ki++;
}
print "@keySet\n";
__END__
--
,-/- __ _ _ $Bill Luebkert ICQ=14439852
(_/ / ) // // DBE Collectibles Mailto:[EMAIL PROTECTED]
/ ) /--< o // // http://dbecoll.tripod.com/ (Free site for Perl)
-/-' /___/_<_</_</_ Castle of Medieval Myth & Magic http://www.todbe.com/
_______________________________________________
ActivePerl mailing list
[EMAIL PROTECTED]
http://listserv.ActiveState.com/mailman/listinfo/activeperl