O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.5. Hash Slices

Like an array variable (or list literal), a hash can be sliced to access a collection of elements instead of just one element at a time. For example, consider the bowling scores set individually:

$score{"fred"} = 205;
$score{"barney"} = 195;
$score{"dino"} = 30;

This seems rather redundant, and in fact can be shortened to:

($score{"fred"},$score{"barney"},$score{"dino"}) =
    (205,195,30);

But even these seems redundant. Let's use a hash slice:

@score{"fred","barney","dino"} = (205,195,30);

There. Much shorter. We can use a hash slice with variable interpolation as well:

@players = qw(fred barney dino);
print "scores are: @score{@players}\n";

Hash slices can also be used to merge a smaller hash into a larger one. In this example, the smaller hash takes precedence in the sense that if there are duplicate keys, the value from the smaller hash is used:

%league{keys %score} = values %score;

Here, the values of %score are merged into the %league hash. This is equivalent to the much slower operation:

%league = (%league, %score); # merge %score into %league

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required