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

I just got some code from a friend with a for loop
for (1 ... #$array) { print $_; }
I was wondering if there were a way to nest two for loops like that. For example
for ( 1 ... $#array) { for (1 ... $#other_array) { print $_; print $_2; # ie the second assumed scalar? } }
Any thoughts?

Replies are listed 'Best First'.
Re: nested for loop with assumed scalars
by Aristotle (Chancellor) on Aug 07, 2004 at 19:38 UTC

    You must name the loop variable for at least one of the loops.

    for my $i ( 1 .. $#array1 ) { for my $j ( 1 .. $#array1 ) { print "$i $j\n"; } }

    Makeshifts last the longest.

Re: nested for loop with assumed scalars
by duff (Parson) on Aug 07, 2004 at 20:10 UTC

    Aristotle already told you what you have to do and the reason why is because automagic assignment to $_ is a short-cut. It's meant as a convience for those situations where you don't really want or need to declare another variable for a simple loop. But when you have multiple nested loops the convience of $_ is largely lost so you should name your loop variables explicitly (all but one of them anyway :).

    Things like $_2 are more obfuscatory than useful IMHO

Re: nested for loop with assumed scalars
by strat (Canon) on Aug 08, 2004 at 09:28 UTC

    EDIT: thanks to Jenda

    beware with

    for my $i (1..$#array) { print "$i: $array[$i]\n"; }
    you'll never get the array element $array[0] because 0 is the first index of an array (well, you could change this behaviour by setting the variable $[ to a nonzero value, but then you get problems with $#array, and IMHO $[ should never be changed because in my eyes changing $[ usually causes more problems than it cures). If you also want to get this, you need to do something like
    for (0..$#array) { print "$i: $array[$i]\n"; }

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"

      I don't understand what do you mean by "problems with $#array". It would still be the index of the last item as defined:

      $[ = 3; @a = (1,2,3,4,5); print $a[$#a];
      but of course I agree it's not a good idea to fiddle with $[.

      Jenda
      Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
         -- Rick Osborne