Friday, September 06, 2013

How to sort a hash in Perl?

Gabor has a nice article about sorting hashes in Perl.

I thought I would piggy-back off Gabor's article and demonstrate how you can do something similar with a couple of CPAN modules specifically designed for processing hashes and lists.

use strict;
use warnings;
use 5.010;
use List::MoreUtils qw(natatime);
use Hash::MoreUtils qw(hashsort);

my %planets = (
    Mercury => 0.4,
    Venus => 0.7,
    Earth => 1,
    Mars => 1.5,
    Ceres => 2.77,
    Jupiter => 5.2,
    Saturn => 9.5,
    Uranus => 19.6,
    Neptune => 30,
    Pluto => 39,
    Charon => 39,
    );

# Sort the keys of the hash using the hashsort function in the  Hash::MoreUtils module
my @array_of_pairs  = hashsort \%planets;

# Leverage List::MoreUtils natatime function to create an iterator to peel off 2 items at a time
my $it = natatime 2, @array_of_pairs;
while ( (my $a, $b) = $it->() ) {
    say "$a $b";
}

__END__

Output...

Ceres 2.77
Charon 39
Earth 1
Jupiter 5.2
Mars 1.5
Mercury 0.4
Neptune 30
Pluto 39
Saturn 9.5
Uranus 19.6
Venus 0.7