in reply to hash sort by the values and get the keys

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

Replies are listed 'Best First'.
Re^2: hash sort by the values and get the keys
by GrandFather (Saint) on May 05, 2009 at 22:04 UTC

    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