This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
(perl #133706) remove exploit code from Storable
[perl5.git] / pod / perllol.pod
CommitLineData
cb1a09d0 1=head1 NAME
4633a7c4 2
19799a22 3perllol - Manipulating Arrays of Arrays in Perl
4633a7c4 4
cb1a09d0
AD
5=head1 DESCRIPTION
6
cea6626f 7=head2 Declaration and Access of Arrays of Arrays
4633a7c4 8
21863e7e
TC
9The simplest two-level data structure to build in Perl is an array of
10arrays, sometimes casually called a list of lists. It's reasonably easy to
11understand, and almost everything that applies here will also be applicable
12later on with the fancier data structures.
4633a7c4 13
19799a22
GS
14An array of an array is just a regular old array @AoA that you can
15get at with two subscripts, like C<$AoA[3][2]>. Here's a declaration
16of the array:
4633a7c4 17
21863e7e
TC
18 use 5.010; # so we can use say()
19
19799a22
GS
20 # assign to our array, an array of array references
21 @AoA = (
21863e7e
TC
22 [ "fred", "barney", "pebbles", "bambam", "dino", ],
23 [ "george", "jane", "elroy", "judy", ],
24 [ "homer", "bart", "marge", "maggie", ],
4633a7c4 25 );
21863e7e 26 say $AoA[2][1];
4633a7c4
LW
27 bart
28
29Now you should be very careful that the outer bracket type
5a964f20 30is a round one, that is, a parenthesis. That's because you're assigning to
19799a22 31an @array, so you need parentheses. If you wanted there I<not> to be an @AoA,
4633a7c4
LW
32but rather just a reference to it, you could do something more like this:
33
19799a22
GS
34 # assign a reference to array of array references
35 $ref_to_AoA = [
4633a7c4 36 [ "fred", "barney", "pebbles", "bambam", "dino", ],
c2611fb3 37 [ "george", "jane", "elroy", "judy", ],
21863e7e 38 [ "homer", "bart", "marge", "maggie", ],
4633a7c4 39 ];
21863e7e
TC
40 say $ref_to_AoA->[2][1];
41 bart
4633a7c4 42
54310121 43Notice that the outer bracket type has changed, and so our access syntax
4633a7c4 44has also changed. That's because unlike C, in perl you can't freely
19799a22
GS
45interchange arrays and references thereto. $ref_to_AoA is a reference to an
46array, whereas @AoA is an array proper. Likewise, C<$AoA[2]> is not an
4633a7c4
LW
47array, but an array ref. So how come you can write these:
48
19799a22
GS
49 $AoA[2][2]
50 $ref_to_AoA->[2][2]
4633a7c4
LW
51
52instead of having to write these:
53
19799a22
GS
54 $AoA[2]->[2]
55 $ref_to_AoA->[2]->[2]
4633a7c4
LW
56
57Well, that's because the rule is that on adjacent brackets only (whether
1fef88e7 58square or curly), you are free to omit the pointer dereferencing arrow.
4d9142af 59But you cannot do so for the very first one if it's a scalar containing
19799a22 60a reference, which means that $ref_to_AoA always needs it.
4633a7c4 61
cea6626f 62=head2 Growing Your Own
4633a7c4
LW
63
64That's all well and good for declaration of a fixed data structure,
65but what if you wanted to add new elements on the fly, or build
66it up entirely from scratch?
67
68First, let's look at reading it in from a file. This is something like
69adding a row at a time. We'll assume that there's a flat file in which
70each line is a row and each word an element. If you're trying to develop an
19799a22 71@AoA array containing all these, here's the right way to do that:
4633a7c4
LW
72
73 while (<>) {
74 @tmp = split;
19799a22 75 push @AoA, [ @tmp ];
54310121 76 }
4633a7c4
LW
77
78You might also have loaded that from a function:
79
80 for $i ( 1 .. 10 ) {
19799a22 81 $AoA[$i] = [ somefunc($i) ];
4633a7c4
LW
82 }
83
84Or you might have had a temporary variable sitting around with the
19799a22 85array in it.
4633a7c4
LW
86
87 for $i ( 1 .. 10 ) {
88 @tmp = somefunc($i);
19799a22 89 $AoA[$i] = [ @tmp ];
4633a7c4
LW
90 }
91
21863e7e
TC
92It's important you make sure to use the C<[ ]> array reference
93constructor. That's because this wouldn't work:
4633a7c4 94
21863e7e 95 $AoA[$i] = @tmp; # WRONG!
4633a7c4 96
21863e7e
TC
97The reason that doesn't do what you want is because assigning a
98named array like that to a scalar is taking an array in scalar
99context, which means just counts the number of elements in @tmp.
4633a7c4 100
21863e7e
TC
101If you are running under C<use strict> (and if you aren't, why in
102the world aren't you?), you'll have to add some declarations to
103make it happy:
4633a7c4
LW
104
105 use strict;
19799a22 106 my(@AoA, @tmp);
4633a7c4
LW
107 while (<>) {
108 @tmp = split;
19799a22 109 push @AoA, [ @tmp ];
54310121 110 }
4633a7c4
LW
111
112Of course, you don't need the temporary array to have a name at all:
113
114 while (<>) {
19799a22 115 push @AoA, [ split ];
54310121 116 }
4633a7c4
LW
117
118You also don't have to use push(). You could just make a direct assignment
119if you knew where you wanted to put it:
120
19799a22 121 my (@AoA, $i, $line);
1fef88e7 122 for $i ( 0 .. 10 ) {
4633a7c4 123 $line = <>;
21863e7e 124 $AoA[$i] = [ split " ", $line ];
54310121 125 }
4633a7c4
LW
126
127or even just
128
19799a22 129 my (@AoA, $i);
1fef88e7 130 for $i ( 0 .. 10 ) {
21863e7e 131 $AoA[$i] = [ split " ", <> ];
54310121 132 }
4633a7c4 133
19799a22
GS
134You should in general be leery of using functions that could
135potentially return lists in scalar context without explicitly stating
136such. This would be clearer to the casual reader:
4633a7c4 137
19799a22 138 my (@AoA, $i);
1fef88e7 139 for $i ( 0 .. 10 ) {
21863e7e 140 $AoA[$i] = [ split " ", scalar(<>) ];
54310121 141 }
4633a7c4 142
19799a22 143If you wanted to have a $ref_to_AoA variable as a reference to an array,
4633a7c4
LW
144you'd have to do something like this:
145
146 while (<>) {
19799a22 147 push @$ref_to_AoA, [ split ];
54310121 148 }
4633a7c4 149
5a964f20 150Now you can add new rows. What about adding new columns? If you're
5f05dabc 151dealing with just matrices, it's often easiest to use simple assignment:
4633a7c4
LW
152
153 for $x (1 .. 10) {
154 for $y (1 .. 10) {
19799a22 155 $AoA[$x][$y] = func($x, $y);
4633a7c4
LW
156 }
157 }
158
159 for $x ( 3, 7, 9 ) {
19799a22 160 $AoA[$x][20] += func2($x);
54310121 161 }
4633a7c4 162
54310121 163It doesn't matter whether those elements are already
4633a7c4
LW
164there or not: it'll gladly create them for you, setting
165intervening elements to C<undef> as need be.
166
5f05dabc 167If you wanted just to append to a row, you'd have
4633a7c4
LW
168to do something a bit funnier looking:
169
170 # add new columns to an existing row
21863e7e
TC
171 push @{ $AoA[0] }, "wilma", "betty"; # explicit deref
172
cea6626f 173=head2 Access and Printing
4633a7c4 174
54310121 175Now it's time to print your data structure out. How
5f05dabc 176are you going to do that? Well, if you want only one
4633a7c4
LW
177of the elements, it's trivial:
178
19799a22 179 print $AoA[0][0];
4633a7c4
LW
180
181If you want to print the whole thing, though, you can't
5f05dabc 182say
4633a7c4 183
19799a22 184 print @AoA; # WRONG
4633a7c4 185
5f05dabc 186because you'll get just references listed, and perl will never
54310121 187automatically dereference things for you. Instead, you have to
4633a7c4
LW
188roll yourself a loop or two. This prints the whole structure,
189using the shell-style for() construct to loop across the outer
54310121 190set of subscripts.
4633a7c4 191
19799a22 192 for $aref ( @AoA ) {
21863e7e 193 say "\t [ @$aref ],";
4633a7c4
LW
194 }
195
196If you wanted to keep track of subscripts, you might do this:
197
19799a22 198 for $i ( 0 .. $#AoA ) {
21863e7e 199 say "\t elt $i is [ @{$AoA[$i]} ],";
4633a7c4
LW
200 }
201
202or maybe even this. Notice the inner loop.
203
19799a22
GS
204 for $i ( 0 .. $#AoA ) {
205 for $j ( 0 .. $#{$AoA[$i]} ) {
21863e7e 206 say "elt $i $j is $AoA[$i][$j]";
4633a7c4
LW
207 }
208 }
209
54310121 210As you can see, it's getting a bit complicated. That's why
4633a7c4
LW
211sometimes is easier to take a temporary on your way through:
212
19799a22
GS
213 for $i ( 0 .. $#AoA ) {
214 $aref = $AoA[$i];
4633a7c4 215 for $j ( 0 .. $#{$aref} ) {
21863e7e 216 say "elt $i $j is $AoA[$i][$j]";
4633a7c4
LW
217 }
218 }
219
5f05dabc 220Hmm... that's still a bit ugly. How about this:
4633a7c4 221
19799a22
GS
222 for $i ( 0 .. $#AoA ) {
223 $aref = $AoA[$i];
4633a7c4
LW
224 $n = @$aref - 1;
225 for $j ( 0 .. $n ) {
21863e7e 226 say "elt $i $j is $AoA[$i][$j]";
4633a7c4
LW
227 }
228 }
229
21863e7e
TC
230When you get tired of writing a custom print for your data structures,
231you might look at the standard L<Dumpvalue> or L<Data::Dumper> modules.
232The former is what the Perl debugger uses, while the latter generates
233parsable Perl code. For example:
234
e46aa1dd 235 use v5.14; # using the + prototype, new to v5.14
21863e7e 236
e46aa1dd 237 sub show(+) {
21863e7e
TC
238 require Dumpvalue;
239 state $prettily = new Dumpvalue::
240 tick => q("),
e46aa1dd
KW
241 compactDump => 1, # comment these two lines
242 # out
243 veryCompact => 1, # if you want a bigger
244 # dump
21863e7e
TC
245 ;
246 dumpValue $prettily @_;
e46aa1dd 247 }
21863e7e 248
e46aa1dd
KW
249 # Assign a list of array references to an array.
250 my @AoA = (
21863e7e
TC
251 [ "fred", "barney" ],
252 [ "george", "jane", "elroy" ],
253 [ "homer", "marge", "bart" ],
e46aa1dd 254 );
10d36cf9 255 push @{ $AoA[0] }, "wilma", "betty";
e46aa1dd 256 show @AoA;
21863e7e
TC
257
258will print out:
259
260 0 0..3 "fred" "barney" "wilma" "betty"
261 1 0..2 "george" "jane" "elroy"
262 2 0..2 "homer" "marge" "bart"
263
264Whereas if you comment out the two lines I said you might wish to,
265then it shows it to you this way instead:
266
267 0 ARRAY(0x8031d0)
268 0 "fred"
269 1 "barney"
270 2 "wilma"
271 3 "betty"
272 1 ARRAY(0x803d40)
273 0 "george"
274 1 "jane"
275 2 "elroy"
276 2 ARRAY(0x803e10)
277 0 "homer"
278 1 "marge"
279 2 "bart"
280
cea6626f 281=head2 Slices
4633a7c4 282
4d9142af 283If you want to get at a slice (part of a row) in a multidimensional
4633a7c4
LW
284array, you're going to have to do some fancy subscripting. That's
285because while we have a nice synonym for single elements via the
286pointer arrow for dereferencing, no such convenience exists for slices.
4633a7c4 287
19799a22 288Here's how to do one operation using a loop. We'll assume an @AoA
4633a7c4
LW
289variable as before.
290
291 @part = ();
54310121 292 $x = 4;
4633a7c4 293 for ($y = 7; $y < 13; $y++) {
19799a22 294 push @part, $AoA[$x][$y];
54310121 295 }
4633a7c4
LW
296
297That same loop could be replaced with a slice operation:
298
21863e7e
TC
299 @part = @{$AoA[4]}[7..12];
300
301or spaced out a bit:
302
19799a22 303 @part = @{ $AoA[4] } [ 7..12 ];
4633a7c4 304
21863e7e 305But as you might well imagine, this can get pretty rough on the reader.
4633a7c4
LW
306
307Ah, but what if you wanted a I<two-dimensional slice>, such as having
5f05dabc 308$x run from 4..8 and $y run from 7 to 12? Hmm... here's the simple way:
4633a7c4 309
19799a22 310 @newAoA = ();
4633a7c4 311 for ($startx = $x = 4; $x <= 8; $x++) {
3e3baf6d 312 for ($starty = $y = 7; $y <= 12; $y++) {
19799a22 313 $newAoA[$x - $startx][$y - $starty] = $AoA[$x][$y];
4633a7c4 314 }
54310121 315 }
4633a7c4 316
54310121 317We can reduce some of the looping through slices
4633a7c4
LW
318
319 for ($x = 4; $x <= 8; $x++) {
19799a22 320 push @newAoA, [ @{ $AoA[$x] } [ 7..12 ] ];
4633a7c4
LW
321 }
322
323If you were into Schwartzian Transforms, you would probably
324have selected map for that
325
19799a22 326 @newAoA = map { [ @{ $AoA[$_] } [ 7..12 ] ] } 4 .. 8;
4633a7c4 327
384f06ae 328Although if your manager accused you of seeking job security (or rapid
4633a7c4
LW
329insecurity) through inscrutable code, it would be hard to argue. :-)
330If I were you, I'd put that in a function:
331
19799a22 332 @newAoA = splice_2D( \@AoA, 4 => 8, 7 => 12 );
4633a7c4 333 sub splice_2D {
19799a22 334 my $lrr = shift; # ref to array of array refs!
54310121 335 my ($x_lo, $x_hi,
4633a7c4
LW
336 $y_lo, $y_hi) = @_;
337
54310121 338 return map {
339 [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
4633a7c4 340 } $x_lo .. $x_hi;
54310121 341 }
4633a7c4
LW
342
343
4633a7c4
LW
344=head1 SEE ALSO
345
ba555bf5 346L<perldata>, L<perlref>, L<perldsc>
4633a7c4
LW
347
348=head1 AUTHOR
349
9607fc9c 350Tom Christiansen <F<tchrist@perl.com>>
4633a7c4 351
21863e7e 352Last update: Tue Apr 26 18:30:55 MDT 2011