Saturday, February 01, 2014

Perl : gettting a list of values from a hash

This is trivial, but since I haven't seen it anywhere on the web, I thought it was worth sharing.

It's pretty common in Perl scripting to have a hash of values, and to want to get the values as a list sorted by the keys. (Actually, that's often why you created the hash in the first place.

Suppose you have a hash like so:

my %things = (
    ddd => 'Dennis',
    ttt => 'Tom',
    mmm => 'Mickey',
    aaa => 'Albert',

To get the values as a list sorted by the keys, the usual suggested method is this:

my @list;
foreach (sort keys %things) {
    push @list, $things{$_};

which is fine, and has the advantage of being totally obvious to anyone reading your code.

But there is another method which will do the same thing in one line:

my @list = map { "$things{$_}" } sort keys %things;

As I said, trivial, but worth documenting for others. And isn't every program just a collection of trivial elements?