Handling two dimensional arrays in Perl is giving me a headache. Anyway, the following is my question:
I have a loop which pushes an array, say @twoOneArray, into another array, say @twoDimArray, and then is reset before the next iteration of loop begins and then again is pushed into @twoDimArray with new set of values. When I print this @twoDimArray using either:
print Dumper \@twoDimArray;
it gives output
OUTPUT
$VAR1 = [
[
'BB',
'AA',
'AA'
],
$VAR1->[0],
$VAR1->[0],
$VAR1->[0]
];
or using loops
for (my $i=0; $i<4; $i++){
for (my $j=0; $j<4; $j++){
print "$twoDimArray[$i][$j] \n";
}
}
the data gets duplicated.
OUTPUT
Row=0 BB AA AA
Row=1 BB AA AA
Row=2 BB AA AA
Row=3 BB AA AA
and so on....
I cant figure out why the both the output ways are going wrong. If I print @twoDimArray everytime (before moving to next iteration of loop, i.e. after using push function) @twoOneArray is inserted, then the values seem to be fine and not repeat themselves, but printing it in a single go seems to give the above error. Similar question has been asked here but I am not sure if it makes sense to me. Any suggestions?
Code to build 2D array:
for ($k = 1; $k <= $counter; $k++){
@twoOneArray = (); #reset it when loop starts again
for ($j = 0; $j <= $colsInArray; $j++){
#do stuff to create @twoOneDim
}
push @twoDimArray, \@twoOneArray;
#if I print @twoDimArray if prints fine, with the exact values intact
}
print Dumper \@twoDimArray; #if I print it here it messes up
print "\n";