How can I print a two-dimensional array in Perl?

multidimensional-array, perl

Solution

Is you array correctly defined? You should use an `@` for an array and a `$` for a scalar... Check this article for a quick reference.

That article gives this simple example.

@matrix = (
        [3, 4, 10],
        [2, 7, 12],
        [0, 3, 4],
        [6, 5, 9],
      );

This creates an array with four rows and three columns. To print the elements of the array, type:

for($row = 0; $row < 4; $row++) {
    for($col = 0; $col < 3; $col++) {
        print "$matrix[$row][$col] ";
    }
    print "\n";
}

Problem

I have a two-dimensional array. When I print/dump this I get the following My two-dimensional array: ``` push (@matrix, \@a1Comparea2); push (@matrix, \@a3Comparea4); ``` a1Comparea2 should be the first row of the array. a3Comparea4 should be the second row of the array. ``` $VAR1 = [ [ '1 6', '2 7', '3 8', '4 9', '5 10' ], $VAR1->[0], $VAR1->[0], $VAR1->[0], $VAR1->[0], [ '7 12', '8 13', '9 14', '10 15', '11 16' ], $VAR1->[5], $VAR1->[5], $VAR1->[5], $VAR1->[5] ]; ``` When I try to print this with the following code: ``` for (my $j= 0; $j < $rows; $j++) { for (my $k= 0; $k < @a1; $k++) { print "Row:$j Col:$k = $matrix[$j][$k]\n"; } } ``` I get the following output: ``` Row:0 Col:0 = 1 6 Row:0 Col:1 = 2 7 Row:0 Col:2 = 3 8 Row:0 Col:3 = 4 9 Row:0 Col:4 = 5 10 Row:1 Col:0 = 1 6 Row:1 Col:1 = 2 7 Row:1 Col:2 = 3 8 Row:1 Col:3 = 4 9 Row:1 Col:4 = 5 10 ``` As you can see, the data is duplicated.

Original source