Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 152
  • Last Modified:

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
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
1 Solution
 
Adam314Commented:

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

0
 
marchentCommented:
Here you'll find how to iterate the 2d array with example http://icfun.blogspot.com/2008/03/perl-two-dimensional-array-handling.html
0
 
DJ_AM_JuiceboxAuthor Commented:
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], "  ");  
    }
}
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Adam314Commented:
You are missing the $ in front of rows[$i].  It should be:
The @{$rows[$i]} means:
    take $rows[$i], which is a reference to an array
    Then take that array

Then the $j < mean interpret that array in scalar context, which means return the number of elements in the array.
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], "  ");  
    }
}

Open in new window

0
 
DJ_AM_JuiceboxAuthor Commented:
ok you're right, thanks.
0
 
ozoCommented:
It may be safer to itterate
for my $i( $[ .. $#rows ){ for my $j ( $[ .. $#{$rows[$i]} )
Or a simpler way is
print "@$_\n" for @rows;
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now