3 perlLoL - Manipulating Lists of Lists in Perl
5 =head1 Declaration and Access
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
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:
16 # assign to our array a list of list references
19 [ "george", "jane", "elroy" ],
20 [ "homer", "marge", "bart" ],
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:
31 # assign a reference to list of list references
33 [ "fred", "barney", "pebbles", "bambam", "dino", ],
34 [ "homer", "bart", "marge", "maggie", ],
35 [ "george", "jane", "alroy", "judy", ],
38 print $ref_to_LoL->[2][2];
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:
49 instead of having to write these:
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.
59 =head1 Growing Your Own
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?
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:
75 You might also have loaded that from a function:
78 $LoL[$i] = [ somefunc($i) ];
81 Or you might have had a temporary variable sitting around with the
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:
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.
97 If you are running under C<use strict>, you'll have to add some
98 declarations to make it happy:
107 Of course, you don't need the temporary array to have a name at all:
110 push @LoL, [ split ];
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:
116 my (@LoL, $i, $line);
119 $LoL[$i] = [ split ' ', $line ];
126 $LoL[$i] = [ split ' ', <> ];
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:
135 $LoL[$i] = [ split ' ', scalar(<>) ];
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:
142 push @$ref_to_LoL, [ split ];
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.)
152 push @$ref_to_LoL, [ split ];
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:
160 $LoL[$x][$y] = func($x, $y);
165 $LoL[$x][20] += func2($x);
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.
172 If you just wanted to append to a row, you'd have
173 to do something a bit funnier looking:
175 # add new columns to an existing row
176 push @{ $LoL[0] }, "wilma", "betty";
178 Notice that I I<couldn't> just say:
180 push $LoL[0], "wilma", "betty"; # WRONG!
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.
185 =head1 Access and Printing
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:
193 If you want to print the whole thing, though, you can't
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
205 print "\t [ @$aref ],\n";
208 If you wanted to keep track of subscripts, you might do this:
210 for $i ( 0 .. $#LoL ) {
211 print "\t elt $i is [ @{$LoL[$i]} ],\n";
214 or maybe even this. Notice the inner loop.
216 for $i ( 0 .. $#LoL ) {
217 for $j ( 0 .. $#{$LoL[$i]} ) {
218 print "elt $i $j is $LoL[$i][$j]\n";
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:
225 for $i ( 0 .. $#LoL ) {
227 for $j ( 0 .. $#{$aref} ) {
228 print "elt $i $j is $LoL[$i][$j]\n";
232 Hm... that's still a bit ugly. How about this:
234 for $i ( 0 .. $#LoL ) {
238 print "elt $i $j is $LoL[$i][$j]\n";
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
251 Here's how to do one operation using a loop. We'll assume an @LoL
256 for ($y = 7; $y < 13; $y++) {
257 push @part, $LoL[$x][$y];
260 That same loop could be replaced with a slice operation:
262 @part = @{ $LoL[4] } [ 7..12 ];
264 but as you might well imagine, this is pretty rough on the reader.
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:
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];
276 We can reduce some of the looping through slices
278 for ($x = 4; $x <= 8; $x++) {
279 push @newLoL, [ @{ $LoL[$x] } [ 7..12 ] ];
282 If you were into Schwartzian Transforms, you would probably
283 have selected map for that
285 @newLoL = map { [ @{ $LoL[$_] } [ 7..12 ] ] } 4 .. 8;
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:
291 @newLoL = splice_2D( \@LoL, 4 => 8, 7 => 12 );
293 my $lrr = shift; # ref to list of list refs!
298 [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
303 =head1 Passing Arguments
305 One place where a list of lists crops up is when you pass
306 in several list references to a function. Consider:
308 @tailings = popmany ( \@a, \@b, \@c, \@d );
313 foreach $aref ( @_ ) {
314 push @retlist, pop @$aref;
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.
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.
331 if (ref($_[$i]) ne 'ARRAY') {
332 confess "popmany: arg $i not an array reference\n";
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.
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
347 perldata(1), perlref(1), perldsc(1)
351 Tom Christiansen <tchrist@perl.com>
353 Last udpate: Sat Oct 7 19:35:26 MDT 1995