4b58bee0b2346d04ae77d2891e0dae8741d539d0
[p5sagit/p5-mst-13.2.git] / pod / perllol.pod
1 =head1 TITLE
2
3 perlLoL - Manipulating Lists of Lists in Perl
4
5 =head1 Declaration and Access
6
7 The simplest thing to build is a list of lists (sometimes called an array
8 of arrays).  It's reasonably easy to understand, and almost everything
9 that applies here will also be applicable later on with the fancier data
10 structures.
11
12 A list of lists, or an array of an array if you would, is just a regular
13 old array @LoL that you can get at with two subscripts, like $LoL[3][2].  Here's
14 a declaration of the array:
15
16     # assign to our array a list of list references
17     @LoL = ( 
18            [ "fred", "barney" ],
19            [ "george", "jane", "elroy" ],
20            [ "homer", "marge", "bart" ],
21     );
22
23     print $LoL[2][2];
24   bart
25
26 Now you should be very careful that the outer bracket type
27 is a round one, that is, parentheses.  That's because you're assigning to
28 an @list, so you need parens.  If you wanted there I<not> to be an @LoL,
29 but rather just a reference to it, you could do something more like this:
30
31     # assign a reference to list of list references
32     $ref_to_LoL = [
33         [ "fred", "barney", "pebbles", "bambam", "dino", ],
34         [ "homer", "bart", "marge", "maggie", ],
35         [ "george", "jane", "alroy", "judy", ],
36     ];
37
38     print $ref_to_LoL->[2][2];
39
40 Notice that the outer bracket type has changed, and so our access syntax 
41 has also changed.  That's because unlike C, in perl you can't freely
42 interchange arrays and references thereto.  $ref_to_LoL is a reference to an 
43 array, whereas @LoL is an array proper.  Likewise, $LoL[2] is not an 
44 array, but an array ref.  So how come you can write these:
45
46     $LoL[2][2]
47     $ref_to_LoL->[2][2]
48
49 instead of having to write these:
50
51     $LoL[2]->[2]
52     $ref_to_LoL->[2]->[2]
53
54 Well, that's because the rule is that on adjacent brackets only (whether
55 square or curly), you are free to omit the pointer dereferencing array.
56 But you need not do so for the very first one if it's a scalar containing
57 a reference, which means that $ref_to_LoL always needs it.
58
59 =head1 Growing Your Own
60
61 That's all well and good for declaration of a fixed data structure,
62 but what if you wanted to add new elements on the fly, or build
63 it up entirely from scratch?
64
65 First, let's look at reading it in from a file.  This is something like
66 adding a row at a time.  We'll assume that there's a flat file in which
67 each line is a row and each word an element.  If you're trying to develop an
68 @LoL list containing all these, here's the right way to do that:
69
70     while (<>) {
71         @tmp = split;
72         push @LoL, [ @tmp ];
73     } 
74
75 You might also have loaded that from a function:
76
77     for $i ( 1 .. 10 ) {
78         $LoL[$i] = [ somefunc($i) ];
79     }
80
81 Or you might have had a temporary variable sitting around with the
82 list in it.  
83
84     for $i ( 1 .. 10 ) {
85         @tmp = somefunc($i);
86         $LoL[$i] = [ @tmp ];
87     }
88
89 It's very important that you make sure to use the C<[]> list reference
90 constructor.  That's because this will be very wrong:
91
92     $LoL[$i] = @tmp;
93
94 You see, assigning a named list like that to a scalar just counts the 
95 number of elements in @tmp, which probably isn't what you want.  
96
97 If you are running under C<use strict>, you'll have to add some
98 declarations to make it happy:
99
100     use strict;
101     my(@LoL, @tmp);
102     while (<>) {
103         @tmp = split;
104         push @LoL, [ @tmp ];
105     } 
106
107 Of course, you don't need the temporary array to have a name at all:
108
109     while (<>) {
110         push @LoL, [ split ];
111     } 
112
113 You also don't have to use push().  You could just make a direct assignment
114 if you knew where you wanted to put it:
115
116     my (@LoL, $i, $line);
117     for $i ( 0 .. 10 ) 
118         $line = <>;
119         $LoL[$i] = [ split ' ', $line ];
120     } 
121
122 or even just
123
124     my (@LoL, $i);
125     for $i ( 0 .. 10 ) 
126         $LoL[$i] = [ split ' ', <> ];
127     } 
128
129 You should in general be leary of using potential list functions
130 in a scalar context without explicitly stating such.  
131 This would be clearer to the casual reader:
132
133     my (@LoL, $i);
134     for $i ( 0 .. 10 ) 
135         $LoL[$i] = [ split ' ', scalar(<>) ];
136     } 
137
138 If you wanted to have a $ref_to_LoL variable as a reference to an array,
139 you'd have to do something like this:
140
141     while (<>) {
142         push @$ref_to_LoL, [ split ];
143     } 
144
145 Actually, if you were using strict, you'd not only have to declare $ref_to_LoL as
146 you had to declare @LoL, but you'd I<also> having to initialize it to a
147 reference to an empty list.  (This was a bug in 5.001m that's been fixed
148 for the 5.002 release.)
149
150     my $ref_to_LoL = [];
151     while (<>) {
152         push @$ref_to_LoL, [ split ];
153     } 
154
155 Ok, now you can add new rows.  What about adding new columns?  If you're
156 just dealing with matrices, it's often easiest to use simple assignment:
157
158     for $x (1 .. 10) {
159         for $y (1 .. 10) {
160             $LoL[$x][$y] = func($x, $y);
161         }
162     }
163
164     for $x ( 3, 7, 9 ) {
165         $LoL[$x][20] += func2($x);
166     } 
167
168 It doesn't matter whether those elements are already 
169 there or not: it'll gladly create them for you, setting
170 intervening elements to C<undef> as need be.
171
172 If you just wanted to append to a row, you'd have
173 to do something a bit funnier looking:
174
175     # add new columns to an existing row
176     push @{ $LoL[0] }, "wilma", "betty";
177
178 Notice that I I<couldn't> just say:
179
180     push $LoL[0], "wilma", "betty";  # WRONG!
181
182 In fact, that wouldn't even compile.  How come?  Because the argument
183 to push() must be a real array, not just a reference to such.
184
185 =head1 Access and Printing
186
187 Now it's time to print your data structure out.  How 
188 are you going to do that?  Well, if you only want one
189 of the elements, it's trivial:
190
191     print $LoL[0][0];
192
193 If you want to print the whole thing, though, you can't
194 just say 
195
196     print @LoL;         # WRONG
197
198 because you'll just get references listed, and perl will never
199 automatically dereference things for you.  Instead, you have to 
200 roll yourself a loop or two.  This prints the whole structure,
201 using the shell-style for() construct to loop across the outer
202 set of subscripts.  
203
204     for $aref ( @LoL ) {
205         print "\t [ @$aref ],\n";
206     }
207
208 If you wanted to keep track of subscripts, you might do this:
209
210     for $i ( 0 .. $#LoL ) {
211         print "\t elt $i is [ @{$LoL[$i]} ],\n";
212     }
213
214 or maybe even this.  Notice the inner loop.
215
216     for $i ( 0 .. $#LoL ) {
217         for $j ( 0 .. $#{$LoL[$i]} ) {
218             print "elt $i $j is $LoL[$i][$j]\n";
219         }
220     }
221
222 As you can see, it's getting a bit complicated.  That's why 
223 sometimes is easier to take a temporary on your way through:
224
225     for $i ( 0 .. $#LoL ) {
226         $aref = $LoL[$i];
227         for $j ( 0 .. $#{$aref} ) {
228             print "elt $i $j is $LoL[$i][$j]\n";
229         }
230     }
231
232 Hm... that's still a bit ugly.  How about this:
233
234     for $i ( 0 .. $#LoL ) {
235         $aref = $LoL[$i];
236         $n = @$aref - 1;
237         for $j ( 0 .. $n ) {
238             print "elt $i $j is $LoL[$i][$j]\n";
239         }
240     }
241
242 =head1 Slices
243
244 If you want to get at a slide (part of a row) in a multidimensional
245 array, you're going to have to do some fancy subscripting.  That's
246 because while we have a nice synonym for single elements via the
247 pointer arrow for dereferencing, no such convenience exists for slices.
248 (Remember, of course, that you can always write a loop to do a slice
249 operation.)
250
251 Here's how to do one operation using a loop.  We'll assume an @LoL
252 variable as before.
253
254     @part = ();
255     $x = 4;     
256     for ($y = 7; $y < 13; $y++) {
257         push @part, $LoL[$x][$y];
258     } 
259
260 That same loop could be replaced with a slice operation:
261
262     @part = @{ $LoL[4] } [ 7..12 ];
263
264 but as you might well imagine, this is pretty rough on the reader.
265
266 Ah, but what if you wanted a I<two-dimensional slice>, such as having
267 $x run from 4..8 and $y run from 7 to 12?  Hm... here's the simple way:
268
269     @newLoL = ();
270     for ($startx = $x = 4; $x <= 8; $x++) {
271         for ($starty = $y = 7; $x <= 12; $y++) {
272             $newLoL[$x - $startx][$y - $starty] = $LoL[$x][$y];
273         }
274     } 
275
276 We can reduce some of the looping through slices 
277
278     for ($x = 4; $x <= 8; $x++) {
279         push @newLoL, [ @{ $LoL[$x] } [ 7..12 ] ];
280     }
281
282 If you were into Schwartzian Transforms, you would probably
283 have selected map for that
284
285     @newLoL = map { [ @{ $LoL[$_] } [ 7..12 ] ] } 4 .. 8;
286
287 Although if your manager accused of seeking job security (or rapid
288 insecurity) through inscrutable code, it would be hard to argue. :-)
289 If I were you, I'd put that in a function:
290
291     @newLoL = splice_2D( \@LoL, 4 => 8, 7 => 12 );
292     sub splice_2D {
293         my $lrr = shift;        # ref to list of list refs!
294         my ($x_lo, $x_hi, 
295             $y_lo, $y_hi) = @_;
296
297         return map { 
298             [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ] 
299         } $x_lo .. $x_hi;
300     } 
301
302
303 =head1 Passing Arguments
304
305 One place where a list of lists crops up is when you pass
306 in several list references to a function.  Consider:
307
308     @tailings = popmany ( \@a, \@b, \@c, \@d );
309
310     sub popmany {
311         my $aref;
312         my @retlist = ();
313         foreach $aref ( @_ ) {
314             push @retlist, pop @$aref;
315         } 
316         return @retlist;
317     } 
318
319 This function was designed to pop off the last element from each of
320 its arguments and return those in a list.  In this function, 
321 you can think of @_ as a list of lists.
322
323 Just as a side note, what happens if the function is called with the
324 "wrong" types of arguments?  Normally nothing, but in the case of
325 references, we can be a bit pickier.  This isn't detectable at
326 compile-time (yet--Larry does have a prototype prototype in the works for
327 5.002), but you could check it at run time using the ref() function.
328
329     use Carp;
330     for $i ( 0 .. $#_) {
331         if (ref($_[$i]) ne 'ARRAY') {
332             confess "popmany: arg $i not an array reference\n";
333         }
334     } 
335
336 However, that's not usually necessary unless you want to trap it.  It's
337 also dubious in that it would fail on a real array references blessed into
338 its own class (an object).  But since you're all going to be using
339 C<strict refs>, it would raise an exception anyway even without the die.
340
341 This will matter more to you later on when you start building up 
342 more complex data structures that all aren't woven of the same 
343 cloth, so to speak.
344
345 =head1 SEE ALSO
346
347 perldata(1), perlref(1), perldsc(1)
348
349 =head1 AUTHOR
350
351 Tom Christiansen <tchrist@perl.com>
352
353 Last udpate: Sat Oct  7 19:35:26 MDT 1995