Perl: Sorting an Array of Hashes

Thoughts from the team
By    | June 6, 2008 | Code Snippets

I recently had a scenario where I had an array of hashes. Each hash represented a row of data for a table and I wanted to sort the whole array by the value of one element of the hash. As you’d expect, Perl has a very nice answer to the problem.

Sorting by a Hash Key

The answer is really quite simple and very elegant. Let’s build up an example.

my @data;
push @data, { name => "Item A", price => 9.99 };
push @data, { name => "Item B", price => 4.99 };
push @data, { name => "Item C", price => 7.5};

We now have an array with 3 hashes in. Suppose we want to sort by price, how do we do it?

my @sorted =  sort { $a->{price} <=> $b->{price} } @data;

Perl’s built in sort function allows us to specify a custom sort order. Within the curly braces Perl gives us 2 variables, $a and $b, which reference 2 items to compare. In our case, these are hash references so we can access the elements of the hash and sort by any key we want. A description of the <=> operator can be found on Perlfect. Suppose we want to sort in reverse order?

my @sorted =  sort { $b->{price} <=> $a->{price} } @data;

Simple. You can test this by adding the following line to the bottom of the script.

print join "n", map {$_->{name}." - ".$_->{price}} @sorted;

Which gives us:

Item B - 4.99
Item C - 7.5
Item A - 9.99

More like this