DavidSzczesniak
12/12/2017 - 12:09 PM

Hash Slices

A hash slice is a list of keys or values of a hash indexed in a single operation. It also allows you to retrieve multiple values from a hash more efficiently.

my %cats;
@cats {qw(Jack Brad Mars Grumpy)} = (1) x 4;
# equivalent to:
my %cats = map {$_ => 1} qw{Jack Brad Mars Grumpy};

# Retrieve multiple values from a hash and assign them to another variable
my @buyer_addresses = @addresses{@buyers);

# Merge two hashes
my %addresses = (...);
my %canada_addresses = (...);

# Targets the keys in %canada_addresses, then takes the values from that hash
@addresses {keys %canada_addresses} = values %canada_addresses;
# note:if the same key occurs in both hashes,
# the hash slice will overwrite existing key/value pairs in %addresses