vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

Is this is the correct and best way to sort an hash by values so I can get the keys according to that ? do you know any other way to do this task. efficient way always welcome

my %hash = (value1 => 345, value2 => 132, value3 => 1, value4 => 12, v +alue5=>978); my (@keys,$key); @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash; foreach $key (@keys) { print "$key: $hash{$key}\n"; }
Vinoth,G

Replies are listed 'Best First'.
Re: hash sort by the values and get the keys
by ELISHEVA (Prior) on May 05, 2009 at 06:12 UTC

    Yes, that is the usual way it is done. The perl reference documentation article sort has a nice discussion with several examples and some hints about making sorts efficient.

    BTW, if you are only using $key to handle the array elements, you can declare it directly in the foreach loop. That is considered better practice because it keeps the variable as close as possible to where it is actually used:

    foreach my $key (@keys) { print "$key: $hash{$key}\n"; }

    Best, beth

      Or:

      for my $key (sort {$hash{$a} <=> $hash{$b}} keys %hash) { print "$key: $hash{$key}\n"; }

      or maybe even:

      print "$_: $hash{$_}\n" for sort {$hash{$a} <=> $hash{$b}} keys %hash;

      True laziness is hard work
Re: hash sort by the values and get the keys
by leslie (Pilgrim) on May 05, 2009 at 05:07 UTC
    Dear friends,
    You can gone through the bellow link for sorting.
    Sort
Re: hash sort by the values and get the keys
by Bloodnok (Vicar) on May 05, 2009 at 09:32 UTC