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

Hi Monks,

Why is it that this runs:

$ perl -e 'for $a (1..2){for $b (10..12){print "$a-$b\n"}}'
1-10
1-11
1-12
2-10
2-11
2-12
and this runs:
$ perl -e 'for $a (1..2){print "$a-$_\n" for (10..12)}'
1-10
1-11
1-12
2-10
2-11
2-12
but this crashes with a syntax error:
$ perl -e 'for $a (1..2){print "$a-$b\n" for $b (10..20)}'
syntax error at -e line 1, near "$b ("
Execution of -e aborted due to compilation errors.
in Perl v5.10.1.

Thanks for your time!
Tel2

Replies are listed 'Best First'.
Re: Syntax error with nested for loop
by Athanasius (Archbishop) on Sep 22, 2015 at 07:41 UTC

    Hello tel2,

    In the first snippet, the inner foreach loop is followed by a code block. But in the second and third snippets, the for is actually a statement modifier, which, as a matter of Perl syntax, has to use $_ as the loop variable. So in the third snippet, the attempt to use $b in place of $_ results in a syntax error. See perlsyn#Statement-Modifiers.

    Update: Made correction re the second snippet, in which the for is also a statement modifier; also improved wording.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Thanks very much for that lightning fast and well explained answer, Athanasius!
Re: Syntax error with nested for loop
by Myrddin Wyllt (Hermit) on Sep 22, 2015 at 13:03 UTC

    Hi Tel2

    Not directly related to your question, which was answered by Athanasius, but just to point out that it's a bad idea to use $a and $b as example variables, as they have a special meaning in perl.

    Common practice is to use  $foo, $bar, $baz etc. for that sort of thing

      Thanks Myrddin.

      Good thing I wasn't trying to sort anything in this example code, I guess.

Re: Syntax error with nested for loop
by u65 (Chaplain) on Sep 22, 2015 at 22:18 UTC

    For future reference in similar cases, converting the one-liner to one statement per line in a conventional script will aid debugging. Using scoped variables with use strict; use warnings; will help even more.

    Update: BTW, I rarely use one-liners. In my typical workflow over the years, any experimental code I try I figure I will reuse so I put it in an executable program from the beginning. My guess is that Windows Perl users may use one-liners more because, IMHO, it may be easier than starting a one-off script in that environment.