Adam Millerchip
Adam Millerchip

Reputation: 23091

Perl slices and references

I created the following slice:

my %hash = ( a => 1, b => 2, c => 3 );
my @backslashed_slice_result = \@hash{qw(a b c)};
#  $backslashed... <-- originally I wrote this is a scalar, see below.

I expected this to produce an array reference to an array populated by the hash slice, equivalent to:

my $arrayref_containing_slice = [ @hash{qw(a b c)} ]; # [1, 2, 3]

But actually is doing something more like:

my @mapped_list_of_values_to_refs = map { \$hash{$_} } qw(a b c); # (\1, \2, \3)

The main point I could find in the documentation that describes this behaviour is the statement:

A slice accesses several elements of a list, an array, or a hash simultaneously using a list of subscripts.

So is \@hash{qw(a b c)} actually a list slice, rather than a hash slice? I am surprised at the reference being taken of the values of the hash, instead of of the resulting array of values. What is it about the syntax that causes perl to apply the leading \ to the values of the hash?

Upvotes: 0

Views: 129

Answers (1)

ysth
ysth

Reputation: 98398

Two points:

First, a hash slice does not produce an array, it produces a list of the sliced hash elements.

Second, using \ on a list produces a list of references to the elements of the first list.

Upvotes: 3

Related Questions