Arrays #6

#0 | #1 | #2 | #3 | #4 | #5 | #6 | #7

Multi-dimensional arrays

In Perl, all arrays are one-dimensional, but the values in each dimension can be references to other arrays. We use the term multi-dimensional loosely.

If you have ever used a spreadsheet, you know what a 2-dimensional array looks like.

In a spreadsheet, you refer to a cell using the row and column labels.

Sounds like a Cartesian plane from geometry, where you use x and y to specify a point on the plane.

In our previous arrays, we referred to an element in the array using a single index into the array: $array[7]

Think of those arrays as only having 1 column (or 1 row if that's easier) - thus we only need 1 index.

So it should come as no surprise that we refer to an element in a 2-dimensional array like this: $array[7][9]

What does a 2-dimensional array look like?

my @foodstuff = (

Using our knowledge of 1-dimensional arrays, how would we refer to sprouts in this array? (remember starting at 0)

If you said $foodstuff[0][1] then you get a plateful of them!

print "Do you like $foodstuff[0][1]?\n";

Each row is indexed starting at 0
Each element of each row is indexed starting at 0

Therefore, this 2-dimensional array is actually an array of arrays.

To print the whole array:

for my $outerloop (0 .. 1) {
    for my $innerloop(0 .. 3) {
        print "$foodstuff[$outerloop][$innerloop], ";
    print "\n";

One thing of note is that we had to specify the number of rows and the number of elements in our code. But what if we don't know either?

my @foodstuff = (

This is where we use a reference to the array: @$.

for my $row (@foodstuff) {
    print "@$row\n";

Or using subscripts (indices):

for my $i (0 .. $#foodstuff) {
    print "Row $i: @{$foodstuff[$i]}\n";

Finally, using an inner and outer loop:

for my $i (0 .. $#foodstuff) {
    for my $j (0 .. $#{$foodstuff[$i]} ) {
        print "Item $i $j: $foodstuff[$i][$j]\n";

We saw the use of $# before for finding the length of an array. We used it again in these examples in our loops.

Arrays are not limited to 2 dimensions - we can have multiple dimensions, as long as we can design, build, and maintain the memory structure.

Next ... Unique stuff