fionbarr has asked for the wisdom of the Perl Monks concerning the following question:

@$var_ref_array = ( [ 5349, 5350, 6205 ], # windows [ 5355, 5356, 1777741, 1777742 ], # linux [ 5699, 1792850, 1792851 ] # solaris
I am trying to iterate through this array and want to make the array size dynamic. The framework looks like:
for my $i ( 0 .. ? ) { for my $j ( 0 .. ?) ) {
I can't get the length correct.

Replies are listed 'Best First'.
Re: iterate through two-dimensional array
by BrowserUk (Patriarch) on Sep 24, 2014 at 20:27 UTC

    for my $i ( 0 .. $#{ $var_ref_array } ) { for my $j ( 0 .. $#{ $var_ref_array->[ $i ] }) ) {

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: iterate through two-dimensional array
by LanX (Saint) on Sep 24, 2014 at 20:37 UTC
    TIMTOWTDI

    DB<102> $var_ref_array = [ [5349, 5350, 6205], [5355, 5356, 1777741, 1777742], [5699, 1792850, 1792851], ] DB<103> for my $a1 (@$var_ref_array) { for my $a2 (@$a1) { print "$a2\t"; } print "\n"; } 5349 5350 6205 5355 5356 1777741 1777742 5699 1792850 1792851

    if you need indeces you can still manually increment something like $i and $j.

    There should also be an each ARRAY solution to get index and value simultaneously but my Perl is too old. :)

    Cheers Rolf

    (addicted to the Perl Programming Language and ☆☆☆☆ :)

      thanks very kindly
Re: iterate through two-dimensional array
by Laurent_R (Canon) on Sep 24, 2014 at 21:24 UTC
    There is not even a need to use declared variables in the for loops, Perl manages nested values of $_ fairly well:
    DB<1> $var_ref_array = [ [ 5349, 5350, 6205 ],[ 5355, 5356, 17 +77741, 1777742 ],[ 5699, 1792850, 1792851 ] ]; DB<2> for (@$var_ref_array) { for (@$_) { print "$_ \t";} print "\n" +}; 5349 5350 6205 5355 5356 1777741 1777742 5699 1792850 1792851
    Or even slightly simpler:
    DB<3> for (@$var_ref_array) { print "$_ \t" for @$_; print "\n";} 5349 5350 6205 5355 5356 1777741 1777742 5699 1792850 1792851
    Having shown that, this is for fun, I should add this may not be not a coding style that I would necessarily recommend.