Skip navigation.
Home
Your source for Perl tips, howto's, faq and tutorials
( categories: )

Slice is the process of obtaining multiple values of a hash in a single operation (the same definition applies for an array, btw). The result of this operation is a list of values.
 
The syntax for hash slicing is very similar to the syntax used to obtain a single element, the difference is that you replace the '$' sigil with '@' and specify a list of keys instead of specifying a single one:

my %hash = ( alpha => 1, beta => 2, gamma => 3, delta => 4 );
 
#-- get a single element
print $hash{beta}; # prints 2
 
#== get multiple elements (slice)
print @hash{qw(alpha delta)} # prints 14

Slicing hash references

In case of hash references, you have to use the following syntax to slice the hash:

my $hash = { alpha => 1, beta => 2, gamma => 3, delta => 4 };
 
#-- get a single element
print $hash->{beta}; # prints 2
 
#== get multiple elements (slice)
print @$hash{qw(alpha delta)} # prints 14