Mass Deface
to be an @AoA,
but rather just a reference to it, you could do something more like this:
# assign a reference to array of array references
$ref_to_AoA = [
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
];
say $ref_to_AoA->[2][1];
bart
Notice that the outer bracket type has changed, and so our access syntax
has also changed. That's because unlike C, in perl you can't freely
interchange arrays and references thereto. $ref_to_AoA is a reference to an
array, whereas @AoA is an array proper. Likewise, C<$AoA[2]> is not an
array, but an array ref. So how come you can write these:
$AoA[2][2]
$ref_to_AoA->[2][2]
instead of having to write these:
$AoA[2]->[2]
$ref_to_AoA->[2]->[2]
Well, that's because the rule is that on adjacent brackets only (whether
square or curly), you are free to omit the pointer dereferencing arrow.
But you cannot do so for the very first one if it's a scalar containing
a reference, which means that $ref_to_AoA always needs it.
=head2 Growing Your Own
That's all well and good for declaration of a fixed data structure,
but what if you wanted to add new elements on the fly, or build
it up entirely from scratch?
First, let's look at reading it in from a file. This is something like
adding a row at a time. We'll assume that there's a flat file in which
each line is a row and each word an element. If you're trying to develop an
@AoA array containing all these, here's the right way to do that:
while (<>) {
@tmp = split;
push @AoA, [ @tmp ];
}
You might also have loaded that from a function:
for $i ( 1 .. 10 ) {
$AoA[$i] = [ somefunc($i) ];
}
Or you might have had a temporary variable sitting around with the
array in it.
for $i ( 1 .. 10 ) {
@tmp = somefunc($i);
$AoA[$i] = [ @tmp ];
}
It's important you make sure to use the C<[ ]> array reference
constructor. That's because this wouldn't work:
$AoA[$i] = @tmp; # WRONG!
The reason that doesn't do what you want is because assigning a
named array like that to a scalar is taking an array in scalar
context, which means just counts the number of elements in @tmp.
If you are running under C