The corrosion of Aaron Stone


Perl Hash Slices

One of my favorite things to do with Perl hashes is slice them with this incredibly concise syntax. The first time I saw this, I Just Got It (TM). Lifting a chunk of text from the excellent (though dated) online book Picking Up Perl, here’s how it works:


It turns out you can slice hashes just like you were able to slice arrays. This can be useful if you need to extract a certain set of values out of a hash into a list.

use strict;
my %table = qw/schmoe joe smith john simpson bart/;
my @friends = @table{'schmoe', 'smith'};
# @friends has qw/joe john/

Note the use of the @ in front of the hash name. This shows that we are indeed producing a normal list, and you can use this construct in any list context you would like.

Context Considerations

We have now discussed all the different ways you can use variables in list and scalar context. At this point, it might be helpful to review all the ways we have used variables in different contexts. The table that follows identifies many of the ways variables are used in Perl.

Expression Context Variable Evaluates to
$scalar scalar $scalar, a scalar the value held in $scalar
@array list @array, an array the list of values (in order) held in @array
@array scalar @array, an array the total number of elements in @array (same as $\#array + 1)
$array\[$x\] scalar @array, an array the ($x+1)th element of @array
$\#array scalar @array, an array the subscript of the last element in @array (same as @array -1)
@array\[$x, $y\] list @array, an array a slice, listing two elements from @array (same as ($array[$x], $array[$y]))
"$scalar" scalar \(interpolated\) $scalar, a scalar a string containing the contents of $scalar
"@array" scalar \(interpolated\) @array, an array a string containing the elements of @array, separated by spaces
%hash list %hash, a hash a list of alternating keys and values from %hash
$hash\{$x\} scalar %hash, a hash the element from %hash with the key of $x
@hash\{$x, $y\} list %hash, a hash a slice, listing two elements from %hash \(same as ($hash\{$x\}, $hash\{$y\}\)