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

Hello,

perl -e 'print $i ++ for 1'
syntax error at -e line 1, near "++ for "
perl -e 'print $i++ for 1'
OK

Replies are listed 'Best First'.
Re: postincrement bug(?) in for
by dsheroh (Monsignor) on Dec 29, 2016 at 11:13 UTC
    Remember that you can print to filehandles stored in scalars: open my $output, '>', 'outfile.txt'; print $output 'foo';

    In your first example, perl is parsing $i as being a filehandle where output should be directed, which then makes the ++ operator the output which should be printed there. But print ++ for 1 is not valid, producing the syntax error you received:

    $ perl -e 'print ++ for 1' syntax error at -e line 1, near "++ for "

    In the second example, $i++ is unambiguous, because you can't increment a filehandle.

Re: postincrement bug(?) in for
by LanX (Saint) on Dec 29, 2016 at 11:11 UTC
    Not a bug, just an undefined situation.

    The parser must often guess which interpretation of the syntax is intended.

    An isolated ++ could be a postincrement, a preincrement or a typo.

    The parser is only playing safe by insisting that there is no gap.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

Re: postincrement bug(?) in for
by kcott (Archbishop) on Dec 29, 2016 at 11:27 UTC

    G'day rsFalse,

    I don't know what your question is. You got a syntax error; you fixed the syntax; the error went away.

    See "perlop: Auto-increment and Auto-decrement". It shows a couple of examples of whitespace between the operator and operand. These are followed by:

    "Perl will not guarantee what the result of the above statements is."

    You should also use these pragmata:

    • strict: which would have told you that $i had not been declared.
    • warnings: which would have told you that $i was uninitialised.

    If you had wanted to operate on the value(s) from for, that may have alerted you to the fact that $i was the wrong variable and you should have been using $_. See "perlsyn -- Perl Syntax".

    — Ken

      Thanks for answers.