DJ_AM_Juicebox
asked on
Getting confused with 2d arrays
Hi,
I just built a 2D array, and I want to iterate over all elements for printing. I tried this:
for ($i = 0; $i < @rows; $i++) {
for ($j = 0; $j < @rows[$i]; $j++) {
print($rows[$i][$j], " ");
}
print("\n");
}
where @rows is my 2D array, but the script just executes in an infinite loop. I'm guessing the problem is:
$j < @rows[$i]
in that statement I mean to say the length of the 1d array in element $i of the 2D array. What's the right syntax for it?
thanks
I just built a 2D array, and I want to iterate over all elements for printing. I tried this:
for ($i = 0; $i < @rows; $i++) {
for ($j = 0; $j < @rows[$i]; $j++) {
print($rows[$i][$j], " ");
}
print("\n");
}
where @rows is my 2D array, but the script just executes in an infinite loop. I'm guessing the problem is:
$j < @rows[$i]
in that statement I mean to say the length of the 1d array in element $i of the 2D array. What's the right syntax for it?
thanks
Here you'll find how to iterate the 2d array with example http://icfun.blogspot.com/2008/03/perl-two-dimensional-array-handling.html
ASKER
Ehh still seems to just loop endlessly. Here's my entire script:
my @rows = ( [2, 4, 6],
[3, 6, 9],
);
for (my $i = 0; $i < @rows; $i++) {
for (my $j = 0; $j < @{rows[$i]}; $j++) {
print($rows[$i][$j], " ");
}
}
my @rows = ( [2, 4, 6],
[3, 6, 9],
);
for (my $i = 0; $i < @rows; $i++) {
for (my $j = 0; $j < @{rows[$i]}; $j++) {
print($rows[$i][$j], " ");
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
ok you're right, thanks.
It may be safer to itterate
for my $i( $[ .. $#rows ){ for my $j ( $[ .. $#{$rows[$i]} )
Or a simpler way is
print "@$_\n" for @rows;
for my $i( $[ .. $#rows ){ for my $j ( $[ .. $#{$rows[$i]} )
Or a simpler way is
print "@$_\n" for @rows;
Open in new window