Sorting hashes in perl
To loop over a sorted hash by it's keys in perl you would normally do the following:
my %hash = ("foo" => 1, "bar" => 2);
foreach my $key (sort keys(%hash)){
print "$key = $hash{$key}\\n";
}
To loop over a hash sorted by it's values you can do this:
my %hash = ("foo" => 1, "bar" => 2);
foreach my $key (sort {$hash{$a} <=> $hash{$b}} keys(%hash)){
print "$key = $hash{$key}\\n";
}
To sort in descending order use:
{$hash{$b} <=> $hash{$a}}
To sort using a string comparison use:
{$hash{$a} cmp $hash{$b}}
Last updated: 25/06/2005