Qiang Li
Qiang Li

Reputation: 10855

The simple way to sort based on values in a hash in Perl

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

Answers (3)

hemanth
hemanth

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

Dave Cross
Dave Cross

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

FMc
FMc

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

Related Questions