[lug] Perl, sorting hashtables by value, and floating-point

Tkil tkil at scrye.com
Mon May 31 23:46:29 MDT 2004


>>>>> "Chris" == Chris Riddoch <chris-blug at syntacticsugar.org> writes:

Chris> Okay, here's the standard Perl idiom for sorting a hash
Chris> numerically by value:

Chris> foreach my $k (sort { $a <=> $b} keys %hash) {
Chris>     print $hash{$k} . " = " . $k . "\n";
Chris> }

Nope, you're sorting the hash *keys* by value.  If you want to get a
list of keys in sorted by their values, you need to compare the values
associated with $a and $b, not $a and $b themselves:

   my @keys_by_value = sort { $hash{$a} <=> $hash{$b} } keys %hash;

And it's a little weird to be printing out "value=key", but without
seeing the rest of your application, I can't decide whether that's an
issue or not.

t.



More information about the LUG mailing list