1PERLLOL(1)             Perl Programmers Reference Guide             PERLLOL(1)
2
3
4

NAME

6       perllol - Manipulating Arrays of Arrays in Perl
7

DESCRIPTION

9       Declaration and Access of Arrays of Arrays
10
11       The simplest thing to build is an array of arrays (sometimes impre‐
12       cisely called a list of lists).  It's reasonably easy to understand,
13       and almost everything that applies here will also be applicable later
14       on with the fancier data structures.
15
16       An array of an array is just a regular old array @AoA that you can get
17       at with two subscripts, like $AoA[3][2].  Here's a declaration of the
18       array:
19
20           # assign to our array, an array of array references
21           @AoA = (
22                  [ "fred", "barney" ],
23                  [ "george", "jane", "elroy" ],
24                  [ "homer", "marge", "bart" ],
25           );
26
27           print $AoA[2][2];
28         bart
29
30       Now you should be very careful that the outer bracket type is a round
31       one, that is, a parenthesis.  That's because you're assigning to an
32       @array, so you need parentheses.  If you wanted there not to be an
33       @AoA, but rather just a reference to it, you could do something more
34       like this:
35
36           # assign a reference to array of array references
37           $ref_to_AoA = [
38               [ "fred", "barney", "pebbles", "bambam", "dino", ],
39               [ "homer", "bart", "marge", "maggie", ],
40               [ "george", "jane", "elroy", "judy", ],
41           ];
42
43           print $ref_to_AoA->[2][2];
44
45       Notice that the outer bracket type has changed, and so our access syn‐
46       tax has also changed.  That's because unlike C, in perl you can't
47       freely interchange arrays and references thereto.  $ref_to_AoA is a
48       reference to an array, whereas @AoA is an array proper.  Likewise,
49       $AoA[2] is not an array, but an array ref.  So how come you can write
50       these:
51
52           $AoA[2][2]
53           $ref_to_AoA->[2][2]
54
55       instead of having to write these:
56
57           $AoA[2]->[2]
58           $ref_to_AoA->[2]->[2]
59
60       Well, that's because the rule is that on adjacent brackets only
61       (whether square or curly), you are free to omit the pointer dereferenc‐
62       ing arrow.  But you cannot do so for the very first one if it's a
63       scalar containing a reference, which means that $ref_to_AoA always
64       needs it.
65
66       Growing Your Own
67
68       That's all well and good for declaration of a fixed data structure, but
69       what if you wanted to add new elements on the fly, or build it up
70       entirely from scratch?
71
72       First, let's look at reading it in from a file.  This is something like
73       adding a row at a time.  We'll assume that there's a flat file in which
74       each line is a row and each word an element.  If you're trying to
75       develop an @AoA array containing all these, here's the right way to do
76       that:
77
78           while (<>) {
79               @tmp = split;
80               push @AoA, [ @tmp ];
81           }
82
83       You might also have loaded that from a function:
84
85           for $i ( 1 .. 10 ) {
86               $AoA[$i] = [ somefunc($i) ];
87           }
88
89       Or you might have had a temporary variable sitting around with the
90       array in it.
91
92           for $i ( 1 .. 10 ) {
93               @tmp = somefunc($i);
94               $AoA[$i] = [ @tmp ];
95           }
96
97       It's very important that you make sure to use the "[]" array reference
98       constructor.  That's because this will be very wrong:
99
100           $AoA[$i] = @tmp;
101
102       You see, assigning a named array like that to a scalar just counts the
103       number of elements in @tmp, which probably isn't what you want.
104
105       If you are running under "use strict", you'll have to add some declara‐
106       tions to make it happy:
107
108           use strict;
109           my(@AoA, @tmp);
110           while (<>) {
111               @tmp = split;
112               push @AoA, [ @tmp ];
113           }
114
115       Of course, you don't need the temporary array to have a name at all:
116
117           while (<>) {
118               push @AoA, [ split ];
119           }
120
121       You also don't have to use push().  You could just make a direct
122       assignment if you knew where you wanted to put it:
123
124           my (@AoA, $i, $line);
125           for $i ( 0 .. 10 ) {
126               $line = <>;
127               $AoA[$i] = [ split ' ', $line ];
128           }
129
130       or even just
131
132           my (@AoA, $i);
133           for $i ( 0 .. 10 ) {
134               $AoA[$i] = [ split ' ', <> ];
135           }
136
137       You should in general be leery of using functions that could poten‐
138       tially return lists in scalar context without explicitly stating such.
139       This would be clearer to the casual reader:
140
141           my (@AoA, $i);
142           for $i ( 0 .. 10 ) {
143               $AoA[$i] = [ split ' ', scalar(<>) ];
144           }
145
146       If you wanted to have a $ref_to_AoA variable as a reference to an
147       array, you'd have to do something like this:
148
149           while (<>) {
150               push @$ref_to_AoA, [ split ];
151           }
152
153       Now you can add new rows.  What about adding new columns?  If you're
154       dealing with just matrices, it's often easiest to use simple assign‐
155       ment:
156
157           for $x (1 .. 10) {
158               for $y (1 .. 10) {
159                   $AoA[$x][$y] = func($x, $y);
160               }
161           }
162
163           for $x ( 3, 7, 9 ) {
164               $AoA[$x][20] += func2($x);
165           }
166
167       It doesn't matter whether those elements are already there or not:
168       it'll gladly create them for you, setting intervening elements to
169       "undef" as need be.
170
171       If you wanted just to append to a row, you'd have to do something a bit
172       funnier looking:
173
174           # add new columns to an existing row
175           push @{ $AoA[0] }, "wilma", "betty";
176
177       Notice that I couldn't say just:
178
179           push $AoA[0], "wilma", "betty";  # WRONG!
180
181       In fact, that wouldn't even compile.  How come?  Because the argument
182       to push() must be a real array, not just a reference to such.
183
184       Access and Printing
185
186       Now it's time to print your data structure out.  How are you going to
187       do that?  Well, if you want only one of the elements, it's trivial:
188
189           print $AoA[0][0];
190
191       If you want to print the whole thing, though, you can't say
192
193           print @AoA;         # WRONG
194
195       because you'll get just references listed, and perl will never automat‐
196       ically dereference things for you.  Instead, you have to roll yourself
197       a loop or two.  This prints the whole structure, using the shell-style
198       for() construct to loop across the outer set of subscripts.
199
200           for $aref ( @AoA ) {
201               print "\t [ @$aref ],\n";
202           }
203
204       If you wanted to keep track of subscripts, you might do this:
205
206           for $i ( 0 .. $#AoA ) {
207               print "\t elt $i is [ @{$AoA[$i]} ],\n";
208           }
209
210       or maybe even this.  Notice the inner loop.
211
212           for $i ( 0 .. $#AoA ) {
213               for $j ( 0 .. $#{$AoA[$i]} ) {
214                   print "elt $i $j is $AoA[$i][$j]\n";
215               }
216           }
217
218       As you can see, it's getting a bit complicated.  That's why sometimes
219       is easier to take a temporary on your way through:
220
221           for $i ( 0 .. $#AoA ) {
222               $aref = $AoA[$i];
223               for $j ( 0 .. $#{$aref} ) {
224                   print "elt $i $j is $AoA[$i][$j]\n";
225               }
226           }
227
228       Hmm... that's still a bit ugly.  How about this:
229
230           for $i ( 0 .. $#AoA ) {
231               $aref = $AoA[$i];
232               $n = @$aref - 1;
233               for $j ( 0 .. $n ) {
234                   print "elt $i $j is $AoA[$i][$j]\n";
235               }
236           }
237
238       Slices
239
240       If you want to get at a slice (part of a row) in a multidimensional
241       array, you're going to have to do some fancy subscripting.  That's
242       because while we have a nice synonym for single elements via the
243       pointer arrow for dereferencing, no such convenience exists for slices.
244       (Remember, of course, that you can always write a loop to do a slice
245       operation.)
246
247       Here's how to do one operation using a loop.  We'll assume an @AoA
248       variable as before.
249
250           @part = ();
251           $x = 4;
252           for ($y = 7; $y < 13; $y++) {
253               push @part, $AoA[$x][$y];
254           }
255
256       That same loop could be replaced with a slice operation:
257
258           @part = @{ $AoA[4] } [ 7..12 ];
259
260       but as you might well imagine, this is pretty rough on the reader.
261
262       Ah, but what if you wanted a two-dimensional slice, such as having $x
263       run from 4..8 and $y run from 7 to 12?  Hmm... here's the simple way:
264
265           @newAoA = ();
266           for ($startx = $x = 4; $x <= 8; $x++) {
267               for ($starty = $y = 7; $y <= 12; $y++) {
268                   $newAoA[$x - $startx][$y - $starty] = $AoA[$x][$y];
269               }
270           }
271
272       We can reduce some of the looping through slices
273
274           for ($x = 4; $x <= 8; $x++) {
275               push @newAoA, [ @{ $AoA[$x] } [ 7..12 ] ];
276           }
277
278       If you were into Schwartzian Transforms, you would probably have
279       selected map for that
280
281           @newAoA = map { [ @{ $AoA[$_] } [ 7..12 ] ] } 4 .. 8;
282
283       Although if your manager accused of seeking job security (or rapid
284       insecurity) through inscrutable code, it would be hard to argue. :-) If
285       I were you, I'd put that in a function:
286
287           @newAoA = splice_2D( \@AoA, 4 => 8, 7 => 12 );
288           sub splice_2D {
289               my $lrr = shift;        # ref to array of array refs!
290               my ($x_lo, $x_hi,
291                   $y_lo, $y_hi) = @_;
292
293               return map {
294                   [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
295               } $x_lo .. $x_hi;
296           }
297

SEE ALSO

299       perldata(1), perlref(1), perldsc(1)
300

AUTHOR

302       Tom Christiansen <tchrist@perl.com>
303
304       Last update: Thu Jun  4 16:16:23 MDT 1998
305
306
307
308perl v5.8.8                       2006-01-07                        PERLLOL(1)
Impressum