Reputation: 10855
Normally sorting based on keys and then iterating a hash can be done as follows:
for $k (sort (keys %h)) {
print $k, $h{$k};
}
But how can I do the sorting based on values and then iterate through the hash? I can think of creating a new hash by swapping the key and value pairs. But is there a cleverer way of doing this?
Upvotes: 3
Views: 8344
Reputation: 352
This sorts the %age hash by value instead of key
@eldest = sort { $age{$b} <=> $age{$a} } keys %age;
This does sorting based on value. For more details refer to Perl Doc:
http://perldoc.perl.org/functions/sort.html
Upvotes: 10
Reputation: 69244
How do I sort a hash (optionally by value instead of key)?
If you're going to program in Perl then you should really take the time to read the FAQ.
Upvotes: 2
Reputation: 42411
If you want the sort comparator to be something other than cmp
, you can supply a code block or a subroutine as the first parameter to sort
. See the documentation for more details.
my %h = (
aaaa => 'z',
bbb => 'x',
c => 'y',
);
# Sort on hash values.
for my $k (sort {$h{$a} cmp $h{$b}} keys %h) {
print $k, "\n"; # bbb c aaaa
}
# Sort using a named subroutine.
for my $k (sort by_length keys %h) {
print $k, "\n"; # c bbb aaaa
}
sub by_length {
length($a) <=> length($b);
}
Upvotes: 6