Search code examples
perlsyntaxpostfix-operator

Why won't Perl let me chain a postfix loop from a postfix comparison?


This is ok:

$foo++ if $condition;

And this is ok:

$foo++ for (1..10);

But this isn't:

$foo++ if $condition for (1..10);

I find the latter quite readable if things aren't complicated, and it fits on one line! Is there a way to do this or should I move on with my life?


Solution

  • You can only have one postfix operation per statement. But you can do what you want (sorta) by using a do block, e.g.

    do { $foo++ if $condition } for ( 1..10 );
    

    Personally, I find this style extremely confusing and difficult to read. I'd avoid it, if I were you. If you're going to all that trouble, you might as well say

    for( 1..10 ) { $foo++ if $condition }
    

    IMHO.