home *** CD-ROM | disk | FTP | other *** search
- <HTML>
- <HEAD>
- <TITLE>perllol - Manipulating Arrays of Arrays in Perl</TITLE>
- <LINK REL="stylesheet" HREF="../../Active.css" TYPE="text/css">
- <LINK REV="made" HREF="mailto:">
- </HEAD>
-
- <BODY>
- <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
- <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
- <STRONG><P CLASS=block> perllol - Manipulating Arrays of Arrays in Perl</P></STRONG>
- </TD></TR>
- </TABLE>
-
- <A NAME="__index__"></A>
- <!-- INDEX BEGIN -->
-
- <UL>
-
- <LI><A HREF="#name">NAME</A></LI>
- <LI><A HREF="#description">DESCRIPTION</A></LI>
- <LI><A HREF="#declaration and access of arrays of arrays">Declaration and Access of Arrays of Arrays</A></LI>
- <LI><A HREF="#growing your own">Growing Your Own</A></LI>
- <LI><A HREF="#access and printing">Access and Printing</A></LI>
- <LI><A HREF="#slices">Slices</A></LI>
- <LI><A HREF="#see also">SEE ALSO</A></LI>
- <LI><A HREF="#author">AUTHOR</A></LI>
- </UL>
- <!-- INDEX END -->
-
- <HR>
- <P>
- <H1><A NAME="name">NAME</A></H1>
- <P>perllol - Manipulating Arrays of Arrays in Perl</P>
- <P>
- <HR>
- <H1><A NAME="description">DESCRIPTION</A></H1>
- <P>
- <HR>
- <H1><A NAME="declaration and access of arrays of arrays">Declaration and Access of Arrays of Arrays</A></H1>
- <P>The simplest thing to build 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.</P>
- <P>An array of an array is just a regular old array @AoA that you can
- get at with two subscripts, like <CODE>$AoA[3][2]</CODE>. Here's a declaration
- of the array:</P>
- <PRE>
- # assign to our array, an array of array references
- @AoA = (
- [ "fred", "barney" ],
- [ "george", "jane", "elroy" ],
- [ "homer", "marge", "bart" ],
- );</PRE>
- <PRE>
- print $AoA[2][2];
- bart</PRE>
- <P>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 <EM>not</EM> to be an @AoA,
- but rather just a reference to it, you could do something more like this:</P>
- <PRE>
- # assign a reference to array of array references
- $ref_to_AoA = [
- [ "fred", "barney", "pebbles", "bambam", "dino", ],
- [ "homer", "bart", "marge", "maggie", ],
- [ "george", "jane", "elroy", "judy", ],
- ];</PRE>
- <PRE>
- print $ref_to_AoA->[2][2];</PRE>
- <P>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, <CODE>$AoA[2]</CODE> is not an
- array, but an array ref. So how come you can write these:</P>
- <PRE>
- $AoA[2][2]
- $ref_to_AoA->[2][2]</PRE>
- <P>instead of having to write these:</P>
- <PRE>
- $AoA[2]->[2]
- $ref_to_AoA->[2]->[2]</PRE>
- <P>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.</P>
- <P>
- <HR>
- <H1><A NAME="growing your own">Growing Your Own</A></H1>
- <P>That's all well and good for declaration of a fixed data structure,
- but what if you wanted to add new elements on the fly, or build
- it up entirely from scratch?</P>
- <P>First, let's look at reading it in from a file. This is something like
- adding a row at a time. We'll assume that there's a flat file in which
- each line is a row and each word an element. If you're trying to develop an
- @AoA array containing all these, here's the right way to do that:</P>
- <PRE>
- while (<>) {
- @tmp = split;
- push @AoA, [ @tmp ];
- }</PRE>
- <P>You might also have loaded that from a function:</P>
- <PRE>
- for $i ( 1 .. 10 ) {
- $AoA[$i] = [ somefunc($i) ];
- }</PRE>
- <P>Or you might have had a temporary variable sitting around with the
- array in it.</P>
- <PRE>
- for $i ( 1 .. 10 ) {
- @tmp = somefunc($i);
- $AoA[$i] = [ @tmp ];
- }</PRE>
- <P>It's very important that you make sure to use the <CODE>[]</CODE> array reference
- constructor. That's because this will be very wrong:</P>
- <PRE>
- $AoA[$i] = @tmp;</PRE>
- <P>You see, assigning a named array like that to a scalar just counts the
- number of elements in @tmp, which probably isn't what you want.</P>
- <P>If you are running under <CODE>use strict</CODE>, you'll have to add some
- declarations to make it happy:</P>
- <PRE>
- use strict;
- my(@AoA, @tmp);
- while (<>) {
- @tmp = split;
- push @AoA, [ @tmp ];
- }</PRE>
- <P>Of course, you don't need the temporary array to have a name at all:</P>
- <PRE>
- while (<>) {
- push @AoA, [ split ];
- }</PRE>
- <P>You also don't have to use push(). You could just make a direct assignment
- if you knew where you wanted to put it:</P>
- <PRE>
- my (@AoA, $i, $line);
- for $i ( 0 .. 10 ) {
- $line = <>;
- $AoA[$i] = [ split ' ', $line ];
- }</PRE>
- <P>or even just</P>
- <PRE>
- my (@AoA, $i);
- for $i ( 0 .. 10 ) {
- $AoA[$i] = [ split ' ', <> ];
- }</PRE>
- <P>You should in general be leery of using functions that could
- potentially return lists in scalar context without explicitly stating
- such. This would be clearer to the casual reader:</P>
- <PRE>
- my (@AoA, $i);
- for $i ( 0 .. 10 ) {
- $AoA[$i] = [ split ' ', scalar(<>) ];
- }</PRE>
- <P>If you wanted to have a $ref_to_AoA variable as a reference to an array,
- you'd have to do something like this:</P>
- <PRE>
- while (<>) {
- push @$ref_to_AoA, [ split ];
- }</PRE>
- <P>Now you can add new rows. What about adding new columns? If you're
- dealing with just matrices, it's often easiest to use simple assignment:</P>
- <PRE>
- for $x (1 .. 10) {
- for $y (1 .. 10) {
- $AoA[$x][$y] = func($x, $y);
- }
- }</PRE>
- <PRE>
- for $x ( 3, 7, 9 ) {
- $AoA[$x][20] += func2($x);
- }</PRE>
- <P>It doesn't matter whether those elements are already
- there or not: it'll gladly create them for you, setting
- intervening elements to <A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> as need be.</P>
- <P>If you wanted just to append to a row, you'd have
- to do something a bit funnier looking:</P>
- <PRE>
- # add new columns to an existing row
- push @{ $AoA[0] }, "wilma", "betty";</PRE>
- <P>Notice that I <EM>couldn't</EM> say just:</P>
- <PRE>
- push $AoA[0], "wilma", "betty"; # WRONG!</PRE>
- <P>In fact, that wouldn't even compile. How come? Because the argument
- to <A HREF="../../lib/Pod/perlfunc.html#item_push"><CODE>push()</CODE></A> must be a real array, not just a reference to such.</P>
- <P>
- <HR>
- <H1><A NAME="access and printing">Access and Printing</A></H1>
- <P>Now it's time to print your data structure out. How
- are you going to do that? Well, if you want only one
- of the elements, it's trivial:</P>
- <PRE>
- print $AoA[0][0];</PRE>
- <P>If you want to print the whole thing, though, you can't
- say</P>
- <PRE>
- print @AoA; # WRONG</PRE>
- <P>because you'll get just references listed, and perl will never
- automatically dereference things for you. Instead, you have to
- roll yourself a loop or two. This prints the whole structure,
- using the shell-style <CODE>for()</CODE> construct to loop across the outer
- set of subscripts.</P>
- <PRE>
- for $aref ( @AoA ) {
- print "\t [ @$aref ],\n";
- }</PRE>
- <P>If you wanted to keep track of subscripts, you might do this:</P>
- <PRE>
- for $i ( 0 .. $#AoA ) {
- print "\t elt $i is [ @{$AoA[$i]} ],\n";
- }</PRE>
- <P>or maybe even this. Notice the inner loop.</P>
- <PRE>
- for $i ( 0 .. $#AoA ) {
- for $j ( 0 .. $#{$AoA[$i]} ) {
- print "elt $i $j is $AoA[$i][$j]\n";
- }
- }</PRE>
- <P>As you can see, it's getting a bit complicated. That's why
- sometimes is easier to take a temporary on your way through:</P>
- <PRE>
- for $i ( 0 .. $#AoA ) {
- $aref = $AoA[$i];
- for $j ( 0 .. $#{$aref} ) {
- print "elt $i $j is $AoA[$i][$j]\n";
- }
- }</PRE>
- <P>Hmm... that's still a bit ugly. How about this:</P>
- <PRE>
- for $i ( 0 .. $#AoA ) {
- $aref = $AoA[$i];
- $n = @$aref - 1;
- for $j ( 0 .. $n ) {
- print "elt $i $j is $AoA[$i][$j]\n";
- }
- }</PRE>
- <P>
- <HR>
- <H1><A NAME="slices">Slices</A></H1>
- <P>If you want to get at a slice (part of a row) in a multidimensional
- array, you're going to have to do some fancy subscripting. That's
- because while we have a nice synonym for single elements via the
- pointer arrow for dereferencing, no such convenience exists for slices.
- (Remember, of course, that you can always write a loop to do a slice
- operation.)</P>
- <P>Here's how to do one operation using a loop. We'll assume an @AoA
- variable as before.</P>
- <PRE>
- @part = ();
- $x = 4;
- for ($y = 7; $y < 13; $y++) {
- push @part, $AoA[$x][$y];
- }</PRE>
- <P>That same loop could be replaced with a slice operation:</P>
- <PRE>
- @part = @{ $AoA[4] } [ 7..12 ];</PRE>
- <P>but as you might well imagine, this is pretty rough on the reader.</P>
- <P>Ah, but what if you wanted a <EM>two-dimensional slice</EM>, such as having
- $x run from 4..8 and $y run from 7 to 12? Hmm... here's the simple way:</P>
- <PRE>
- @newAoA = ();
- for ($startx = $x = 4; $x <= 8; $x++) {
- for ($starty = $y = 7; $y <= 12; $y++) {
- $newAoA[$x - $startx][$y - $starty] = $AoA[$x][$y];
- }
- }</PRE>
- <P>We can reduce some of the looping through slices</P>
- <PRE>
- for ($x = 4; $x <= 8; $x++) {
- push @newAoA, [ @{ $AoA[$x] } [ 7..12 ] ];
- }</PRE>
- <P>If you were into Schwartzian Transforms, you would probably
- have selected map for that</P>
- <PRE>
- @newAoA = map { [ @{ $AoA[$_] } [ 7..12 ] ] } 4 .. 8;</PRE>
- <P>Although if your manager accused of seeking job security (or rapid
- insecurity) through inscrutable code, it would be hard to argue. :-)
- If I were you, I'd put that in a function:</P>
- <PRE>
- @newAoA = splice_2D( \@AoA, 4 => 8, 7 => 12 );
- sub splice_2D {
- my $lrr = shift; # ref to array of array refs!
- my ($x_lo, $x_hi,
- $y_lo, $y_hi) = @_;</PRE>
- <PRE>
- return map {
- [ @{ $lrr->[$_] } [ $y_lo .. $y_hi ] ]
- } $x_lo .. $x_hi;
- }</PRE>
- <P>
- <HR>
- <H1><A NAME="see also">SEE ALSO</A></H1>
- <P>perldata(1), perlref(1), <CODE>perldsc(1)</CODE></P>
- <P>
- <HR>
- <H1><A NAME="author">AUTHOR</A></H1>
- <P>Tom Christiansen <<EM><A HREF="mailto:tchrist@perl.com">tchrist@perl.com</A></EM>></P>
- <P>Last update: Thu Jun 4 16:16:23 MDT 1998</P>
- <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
- <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
- <STRONG><P CLASS=block> perllol - Manipulating Arrays of Arrays in Perl</P></STRONG>
- </TD></TR>
- </TABLE>
-
- </BODY>
-
- </HTML>
-