Hash Slices

Learn about hash slices and empty hashes in Perl.

Introduction to hash slices

A hash slice is a list of keys or values of a hash indexed in a single operation. Here’s how to initialize multiple elements of a hash at once:

Press + to interact
my %cats;
@cats{qw( Jack Brad Mars Grumpy )} = (1) x 4;
# printing the hash
for (keys %cats) {
say "$_ => $cats{$_}";
}

This is equivalent to the following initialization:

Press + to interact
my %cats = map { $_ => 1 } qw( Jack Brad Mars Grumpy );
# printing the hash
for (keys %cats) {
say "$_ => $cats{$_}";
}

Note: The hash slice assignment can also add to the existing contents of the hash.

Retrieving multiple values

Hash slices also allow us to retrieve multiple values from a hash in a single operation. As with array ...