How can I sort a hash's keys naturally?

lamcro picture lamcro · Dec 20, 2008 · Viewed 40.6k times · Source

I have a Perl hash whose keys start with, or are, numbers.

If I use,

foreach my $key (sort keys %hash) {
    print $hash{$key} . "\n";
}

the list might come out as,

0
0001
1000
203
23

Instead of

0
0001
23
203
1000

Answer

Paul Tomblin picture Paul Tomblin · Dec 20, 2008
foreach my $key (sort { $a <=> $b} keys %hash) {
    print $hash{$key} . "\n";
}

The sort operation takes an optional comparison "subroutine" (either as a block of code, as I've done here, or the name of a subroutine). I've supplied an in-line comparison that treats the keys as numbers using the built-in numeric comparison operator '<=>'.