Let's start with the following two assertions:
@a
starts out as an empty array with no elements.
$b
is assigned the value of 10.
Now look at this construct:
@{$a[$b]}
To understand we can start in the middle: $a[$b]
indexes element 10 of the array @a
.
Now we can work outward from there: @{...}
treats its contents as a reference to an array. So @{$a[$b]}
treats the content of element 10 of the array @a
as a reference to an anonymous array. That is to say, the scalar value contained in $a[10]
is an array reference.
Now layer in the push:
push @{$a[$b]}, $c;
Into the anonymous array referenced in element 10 of @a
you are pushing the value of $c
, which is the character "a". You could access that element like this:
my $value = $a[10]->[0]; # character 'a'
Or shorthand,
my $value = $a[10][0];
If you pushed another value into @{$a[10]}
then you would access it at:
my $other_value = $a[10][1];
But what about $a[0]
through $a[9]
? You're only pushing a value into $a[$b]
, which is $a[10]
. Perl automatically extends the array to accommodate that 11th element ($a[10]
), but leaves the value in $a[0]
through $a[9]
as undef
. You mentioned that you tried this:
print "@a\n";
Interpolating an array into a string causes its elements to be printed with a space between each one. So you didn't see this:
ARRAY(0xa6f328)
You saw this:
ARRAY(0xa6f328)
...because there were ten spaces before the 11th element which contains an array reference.
If you were running your script with use warnings
at the top, you would have seen this instead:
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
Use of uninitialized value in join or string at scripts/mytest.pl line 12.
ARRAY(0xa6f328)
...or something quite similar.
Your structure currently looks like this:
@a = (undef,undef,undef,undef,undef,undef,undef,undef,undef,undef,['a'])
If you ever want to really get a look at what a data structure looks like, rather than using a simple print, do something like this:
use Data::Dumper;
print Dumper \@a;