Posts Tagged ‘slice’

Perl Hash Slices

May 22nd, 2014 subogero Comments off

Perl always does what you want, except if you want consistency.

I remember those “Wouldn’t it be great?” moments throughout my Perl hacking years. The answer was invariably “Yes, you can”.

Wouldn’t it be great if you could interpolate variables into regular expressions? Yes. you can.
Wouldn’t it be great if you could address a hash with a subset of keys and get a subset of values? Yes, you can.

Which, in turn, brings me to hash slices and a few related tricks.

Slicing Hashrefs

This is how you slice a hash, building an array of values from an array of corresponding keys. Pythonistas may now notice the beautiful simplicity compared to their silly list comprehensions…

%hash = (one => 1, two => 2, three => 3);
@one_three = @hash{'one', 'three'};

But how to slice a hashref?

$hashref = {one => 1, two => 2, three => 3};
@one_three = @{$hashref}{'one', 'three'};

The rule is that if you have a $hashref instead of a %hash, you can do everything the same way, just replace the bare sigil-less name of the hash with {$hashref}. Pythonistas are at this moment enlightened about the usefulness of sigils.

Merging Hashes

Hash slices can be lvalues too, so you can assign an array of values to an array of keys.

%numbers = (one => 1, two => 2);
%more = (three => 3, four => 4);
@numbers{keys %more} = values %more;

Note the @ sigil in front of all hash slices. They are arrays!

Categories: Uncategorized Tags: , , , ,