views:

965

answers:

2

I have a 2 dimensional array. When I print/Dump this I get the following

My 2 dim array:

push (@matrix, \@a1Comparea2);
push (@matrix, \@a3Comparea4);

a1Comparea2 should be first row of array a3Comparea4 should be second row of 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 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.

A: 

Is you array correctly defined?
You use an @ for array and a $ for 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”;
}
nik
I think as the dump shows, my matrix is defined correctly. I've updated the question to show how my matrix is defined.
You've left something out. You add two array refs, but your dump clearly shows more than that.
Bill
@Bill, I presume you are addressing `rob` who wrote the question.
nik
A: 

Are you sure you used the code you showed above? Maybe you used something like:

for (my $j= 0; $j < $rows; $j++)
{
        for (my $k= 0; $k < @a1; $k++)
        {
                print "Row:$j Col:$k = $matrix[$not_j][$k]\n";
        }
}

$not_j would evaluate always to 0, producing your output.

Curd