in reply to Finding the length of an array of arrays

I think you want this:
my @array = ( [ 1..3 ], [ 2..6 ] ); for my $i (0 .. $#array) { for $k (0..$#{ $array[$i] }) { ## This is the key. print $array[$i][$k]; } }

Replies are listed 'Best First'.
RE (tilly) 2: Finding the length of an array of arrays
by tilly (Archbishop) on Aug 17, 2000 at 23:57 UTC
    It is better IMO to encourage the use of foreach rather than C style loops. (Executes faster, faster to write, easier to avoid logic errors like off by one.)
    my @array = ( [ 1..3 ], [ 2..6 ] ); foreach my $outer (@array) { foreach my $element (@$outer) { print "$element\n"; } }
    OTOH map is really nice...
    my @array = ( [ 1..3 ], [ 2..6 ] ); print map {"$_\n"} map {@$_} @array;
    :-)
      Actually, according to Merlyn, at this node for and foreach are the same and have been since the beginning of Perl. That was all cleared up in for vs foreach.

      Minor point of correction... :)
        No correction in fact. I knew they were aliases all along. But I find it clearer to indicate my thoughts by saying "for" for the classic C loop and "foreach" for iterating over a list. Particularly when I am trying to tell C programmers why they should use foreach style loops rather than for loops. ;-)
RE: Re: Finding the length of an array of arrays
by Boogman (Scribe) on Aug 17, 2000 at 23:43 UTC
    Shouldn't that be print scalar( @$array[$i][$k] ); or print $#$array[$i][$k]; to print the size out. Otherwise your printing the reference to the array, I think.

    Update: oops, sorry. You're right...

    Got confused with the "length of array in array of arrays". Thought that meant the array of arrays held references to arrays again...
      That print line isn't printing the size; I didn't think that was what the OP wanted, from the code he/she demonstrated. It looked like he/she just wanted to find the "length" of the array (actually the last index) in order to loop over the inner arrays, then print out each element. So that's what my code does: the print line is printing the element with index $k in the array at $i in the original array @array.
        You are correct, and the changes you suggested worked perfectly. Thanks.