{
    "mode": "man",
    "parameter": "perllol",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/perllol/1/json",
    "generated": "2026-06-14T01:03:49Z",
    "sections": {
        "NAME": {
            "content": "perllol - Manipulating Arrays of Arrays in Perl\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "",
            "subsections": [
                {
                    "name": "Declaration and Access of Arrays of Arrays",
                    "content": "The simplest two-level data structure to build in Perl is an array of arrays, sometimes\ncasually called a list of lists.  It's reasonably easy to understand, and almost everything\nthat applies here will also be applicable later on with the fancier data structures.\n\nAn array of an array is just a regular old array @AoA that you can get at with two\nsubscripts, like $AoA[3][2].  Here's a declaration of the array:\n\nuse 5.010;  # so we can use say()\n\n# assign to our array, an array of array references\n@AoA = (\n[ \"fred\", \"barney\", \"pebbles\", \"bambam\", \"dino\", ],\n[ \"george\", \"jane\", \"elroy\", \"judy\", ],\n[ \"homer\", \"bart\", \"marge\", \"maggie\", ],\n);\nsay $AoA[2][1];\nbart\n\nNow you should be very careful that the outer bracket type is a round one, that is, a\nparenthesis.  That's because you're assigning to an @array, so you need parentheses.  If you\nwanted there not to be an @AoA, but rather just a reference to it, you could do something\nmore like this:\n\n# assign a reference to array of array references\n$reftoAoA = [\n[ \"fred\", \"barney\", \"pebbles\", \"bambam\", \"dino\", ],\n[ \"george\", \"jane\", \"elroy\", \"judy\", ],\n[ \"homer\", \"bart\", \"marge\", \"maggie\", ],\n];\nsay $reftoAoA->[2][1];\nbart\n\nNotice that the outer bracket type has changed, and so our access syntax has also changed.\nThat's because unlike C, in perl you can't freely interchange arrays and references thereto.\n$reftoAoA is a reference to an array, whereas @AoA is an array proper.  Likewise, $AoA[2]\nis not an array, but an array ref.  So how come you can write these:\n\n$AoA[2][2]\n$reftoAoA->[2][2]\n\ninstead of having to write these:\n\n$AoA[2]->[2]\n$reftoAoA->[2]->[2]\n\nWell, that's because the rule is that on adjacent brackets only (whether square or curly),\nyou are free to omit the pointer dereferencing arrow.  But you cannot do so for the very\nfirst one if it's a scalar containing a reference, which means that $reftoAoA always needs\nit.\n"
                },
                {
                    "name": "Growing Your Own",
                    "content": "That's all well and good for declaration of a fixed data structure, but what if you wanted to\nadd new elements on the fly, or build it up entirely from scratch?\n\nFirst, let's look at reading it in from a file.  This is something like adding a row at a\ntime.  We'll assume that there's a flat file in which each line is a row and each word an\nelement.  If you're trying to develop an @AoA array containing all these, here's the right\nway to do that:\n\nwhile (<>) {\n@tmp = split;\npush @AoA, [ @tmp ];\n}\n\nYou might also have loaded that from a function:\n\nfor $i ( 1 .. 10 ) {\n$AoA[$i] = [ somefunc($i) ];\n}\n\nOr you might have had a temporary variable sitting around with the array in it.\n\nfor $i ( 1 .. 10 ) {\n@tmp = somefunc($i);\n$AoA[$i] = [ @tmp ];\n}\n\nIt's important you make sure to use the \"[ ]\" array reference constructor.  That's because\nthis wouldn't work:\n\n$AoA[$i] = @tmp;   # WRONG!\n\nThe reason that doesn't do what you want is because assigning a named array like that to a\nscalar is taking an array in scalar context, which means just counts the number of elements\nin @tmp.\n\nIf you are running under \"use strict\" (and if you aren't, why in the world aren't you?),\nyou'll have to add some declarations to make it happy:\n\nuse strict;\nmy(@AoA, @tmp);\nwhile (<>) {\n@tmp = split;\npush @AoA, [ @tmp ];\n}\n\nOf course, you don't need the temporary array to have a name at all:\n\nwhile (<>) {\npush @AoA, [ split ];\n}\n\nYou also don't have to use push().  You could just make a direct assignment if you knew where\nyou wanted to put it:\n\nmy (@AoA, $i, $line);\nfor $i ( 0 .. 10 ) {\n$line = <>;\n$AoA[$i] = [ split \" \", $line ];\n}\n\nor even just\n\nmy (@AoA, $i);\nfor $i ( 0 .. 10 ) {\n$AoA[$i] = [ split \" \", <> ];\n}\n\nYou should in general be leery of using functions that could potentially return lists in\nscalar context without explicitly stating such.  This would be clearer to the casual reader:\n\nmy (@AoA, $i);\nfor $i ( 0 .. 10 ) {\n$AoA[$i] = [ split \" \", scalar(<>) ];\n}\n\nIf you wanted to have a $reftoAoA variable as a reference to an array, you'd have to do\nsomething like this:\n\nwhile (<>) {\npush @$reftoAoA, [ split ];\n}\n\nNow you can add new rows.  What about adding new columns?  If you're dealing with just\nmatrices, it's often easiest to use simple assignment:\n\nfor $x (1 .. 10) {\nfor $y (1 .. 10) {\n$AoA[$x][$y] = func($x, $y);\n}\n}\n\nfor $x ( 3, 7, 9 ) {\n$AoA[$x][20] += func2($x);\n}\n\nIt doesn't matter whether those elements are already there or not: it'll gladly create them\nfor you, setting intervening elements to \"undef\" as need be.\n\nIf you wanted just to append to a row, you'd have to do something a bit funnier looking:\n\n# add new columns to an existing row\npush $AoA[0]->@*, \"wilma\", \"betty\";   # explicit deref\n"
                },
                {
                    "name": "Access and Printing",
                    "content": "Now it's time to print your data structure out.  How are you going to do that?  Well, if you\nwant only one of the elements, it's trivial:\n\nprint $AoA[0][0];\n\nIf you want to print the whole thing, though, you can't say\n\nprint @AoA;         # WRONG\n\nbecause you'll get just references listed, and perl will never automatically dereference\nthings for you.  Instead, you have to roll yourself a loop or two.  This prints the whole\nstructure, using the shell-style for() construct to loop across the outer set of subscripts.\n\nfor $aref ( @AoA ) {\nsay \"\\t [ @$aref ],\";\n}\n\nIf you wanted to keep track of subscripts, you might do this:\n\nfor $i ( 0 .. $#AoA ) {\nsay \"\\t elt $i is [ @{$AoA[$i]} ],\";\n}\n\nor maybe even this.  Notice the inner loop.\n\nfor $i ( 0 .. $#AoA ) {\nfor $j ( 0 .. $#{$AoA[$i]} ) {\nsay \"elt $i $j is $AoA[$i][$j]\";\n}\n}\n\nAs you can see, it's getting a bit complicated.  That's why sometimes is easier to take a\ntemporary on your way through:\n\nfor $i ( 0 .. $#AoA ) {\n$aref = $AoA[$i];\nfor $j ( 0 .. $#{$aref} ) {\nsay \"elt $i $j is $AoA[$i][$j]\";\n}\n}\n\nHmm... that's still a bit ugly.  How about this:\n\nfor $i ( 0 .. $#AoA ) {\n$aref = $AoA[$i];\n$n = @$aref - 1;\nfor $j ( 0 .. $n ) {\nsay \"elt $i $j is $AoA[$i][$j]\";\n}\n}\n\nWhen you get tired of writing a custom print for your data structures, you might look at the\nstandard Dumpvalue or Data::Dumper modules.  The former is what the Perl debugger uses, while\nthe latter generates parsable Perl code.  For example:\n\nuse v5.14;     # using the + prototype, new to v5.14\n\nsub show(+) {\nrequire Dumpvalue;\nstate $prettily = new Dumpvalue::\ntick        => q(\"),\ncompactDump => 1,  # comment these two lines\n# out\nveryCompact => 1,  # if you want a bigger\n# dump\n;\ndumpValue $prettily @;\n}\n\n# Assign a list of array references to an array.\nmy @AoA = (\n[ \"fred\", \"barney\" ],\n[ \"george\", \"jane\", \"elroy\" ],\n[ \"homer\", \"marge\", \"bart\" ],\n);\npush $AoA[0]->@*, \"wilma\", \"betty\";\nshow @AoA;\n\nwill print out:\n\n0  0..3  \"fred\" \"barney\" \"wilma\" \"betty\"\n1  0..2  \"george\" \"jane\" \"elroy\"\n2  0..2  \"homer\" \"marge\" \"bart\"\n\nWhereas if you comment out the two lines I said you might wish to, then it shows it to you\nthis way instead:\n\n0  ARRAY(0x8031d0)\n0  \"fred\"\n1  \"barney\"\n2  \"wilma\"\n3  \"betty\"\n1  ARRAY(0x803d40)\n0  \"george\"\n1  \"jane\"\n2  \"elroy\"\n2  ARRAY(0x803e10)\n0  \"homer\"\n1  \"marge\"\n2  \"bart\"\n"
                },
                {
                    "name": "Slices",
                    "content": "If you want to get at a slice (part of a row) in a multidimensional array, you're going to\nhave to do some fancy subscripting.  That's because while we have a nice synonym for single\nelements via the pointer arrow for dereferencing, no such convenience exists for slices.\n\nHere's how to do one operation using a loop.  We'll assume an @AoA variable as before.\n\n@part = ();\n$x = 4;\nfor ($y = 7; $y < 13; $y++) {\npush @part, $AoA[$x][$y];\n}\n\nThat same loop could be replaced with a slice operation:\n\n@part = $AoA[4]->@[ 7..12 ];\n\nNow, what if you wanted a two-dimensional slice, such as having $x run from 4..8 and $y run\nfrom 7 to 12?  Hmm... here's the simple way:\n\n@newAoA = ();\nfor ($startx = $x = 4; $x <= 8; $x++) {\nfor ($starty = $y = 7; $y <= 12; $y++) {\n$newAoA[$x - $startx][$y - $starty] = $AoA[$x][$y];\n}\n}\n\nWe can reduce some of the looping through slices\n\nfor ($x = 4; $x <= 8; $x++) {\npush @newAoA, [ $AoA[$x]->@[ 7..12 ] ];\n}\n\nIf you were into Schwartzian Transforms, you would probably have selected map for that\n\n@newAoA = map { [ $AoA[$]->@[ 7..12 ] ] } 4 .. 8;\n\nAlthough if your manager accused you of seeking job security (or rapid insecurity) through\ninscrutable code, it would be hard to argue. :-) If I were you, I'd put that in a function:\n\n@newAoA = splice2D( \\@AoA, 4 => 8, 7 => 12 );\nsub splice2D {\nmy $lrr = shift;        # ref to array of array refs!\nmy ($xlo, $xhi,\n$ylo, $yhi) = @;\n\nreturn map {\n[ $lrr->[$]->@[ $ylo .. $yhi ] ]\n} $xlo .. $xhi;\n}\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "perldata, perlref, perldsc\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Tom Christiansen <tchrist@perl.com>\n\nLast update: Tue Apr 26 18:30:55 MDT 2011\n\n\n\nperl v5.34.0                                 2025-07-25                                   PERLLOL(1)",
            "subsections": []
        }
    },
    "summary": "perllol - Manipulating Arrays of Arrays in Perl",
    "flags": [],
    "examples": [],
    "see_also": []
}