user166918 user166918 - 24 days ago 7
Perl Question

How do references in Perl work

Can anyone explain the

push
statement in the following Perl code to me? I know how push in perl works but I can't understand what the first argument in following push command represents. I am trying to interpret someone's script. I tried to
print "@a\n";
but it only printed
ARRAY(0x9aa370)
which makes me think that the push is not doing anything. Any help is appreciated. Thanks!

my @a = ();
my $b = 10;
my $c = 'a';
push(@{$a[$b]}, $c);

Answer Source

Let's break it down.

The @{...} is understood from "Using References" in perlref

Anywhere you'd put an identifier (or chain of identifiers) as part of a variable or subroutine name, you can replace the identifier with a BLOCK returning a reference of the correct type.

So what is inside { ... } block had better work out to an array reference. You have $a[$b] there, an element of @a at index $b, so that element must be an arrayref.

Then @{...} dereferences it and pushes a new element $c to it. Altogether, $c is copied into a (sole) element of an anonymous array whose reference is at index $b of the array @a.

And a crucial part: as there is in fact no arrayref there, the autovivification kicks in and it is created. Since there are no elements at indices preceding $b they are created as well, with value undef.

Now please work through

while using perlref for a full reference.


With complex data structures it is useful to be able to see them, and there are tools for that. A most often used one is the core Data::Dumper, and here is an example with Data::Dump

perl -MData::Dump=dd -wE'@ary = (1); push @{$ary[3]}, "ah"; dd \@ary'

with output

[1, undef, undef, ["ah"]]

where [] inside indicate an arrayref, with its sole element being the string ah.


More precisely, an undef scalar is dereferenced and since this happens in an lvalue context the autovivification goes. Thanks to ikegami for a comment. See for instance this post with its links.