Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
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
Avatar of Adam314
Adam314


for(my $i = 0; $i < @rows; $i++) {
	for (my $j = 0; $j < @{$rows[$i]}; $j++) {
		print($rows[$i][$j], "  ");  
	}
	print("\n");
}

Open in new window

Here you'll find how to iterate the 2d array with example http://icfun.blogspot.com/2008/03/perl-two-dimensional-array-handling.html
Avatar of DJ_AM_Juicebox

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], "  ");  
    }
}
ASKER CERTIFIED SOLUTION
Avatar of Adam314
Adam314

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok you're right, thanks.
Avatar of ozo
It may be safer to itterate
for my $i( $[ .. $#rows ){ for my $j ( $[ .. $#{$rows[$i]} )
Or a simpler way is
print "@$_\n" for @rows;