Search code examples
perl

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?


Solution

  • 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);
    }