Manipulating Arrays of Arrays in Perl | Манипулирование массивами массивов в Perl History of edits
(Latest: zibsoft 1 year, 5 months ago)
§ | |
| | |
perllol - Manipulating Arrays of Arrays in Perl | perllol - Манипулирование массивами массивов в Perl History of edits
(Latest: zibsoft 1 year, 5 months ago)
§ | |
| | |
=head2 Declaration and Access of Arrays of Arrays | =head2 Объявление и доступ к массивам массивов History of edits
(Latest: zibsoft 1 year, 5 months ago)
§ | |
The simplest thing to build is an array of arrays (sometimes imprecisely called a list of lists). It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures. | | |
An array of an array is just a regular old array @AoA that you can get at with two subscripts, like C<$AoA[3][2]>. Here's a declaration of the array: | | |
# assign to our array, an array of array references @AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], ); | | |
| | |
Now you should be very careful that the outer bracket type is a round one, that is, a parenthesis. That's because you're assigning to an @array, so you need parentheses. If you wanted there I<not> 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", ], [ "homer", "bart", "marge", "maggie", ], [ "george", "jane", "elroy", "judy", ], ]; | | |
print $ref_to_AoA->[2][2]; | | |
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. | | |