views:

116

answers:

3

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?

+11  A: 

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.

friedo
It's really all the same to me. I just couldn't find anywhere where that was spelled out and was looking for an explanation. Thanks!
wes
+3  A: 

Another way to achieve the same effect as an if statement is with and, so you could say

$condition and $foo++ for 1 .. 10;

However, that is not an encouraged practice.

Chas. Owens
+1  A: 

As I understand it, this was an intentional design decision in the very early days of perl to avoid having people write hard to read or hard to get right code. Perl 6 will allow at least some combinations (if/for and for/if, but not for/for or if/if maybe?) and I believe Perl 5 will follow suit at some point.

Update: Perl 6 will allow a conditional inside a loop (e.g. EXPR if EXPR for LIST ); anything more requires extra parens (e.g. ( EXPR for LIST ) if EXPR ).

ysth
Sometimes I think the last thing on Larry Wall and co.'s minds was preventing unreadable code :D That's one of the joys of Perl, though, the freedom to do what works best for the situation. I'm all for more freedom, even if it gives me a chance to screw myself over.
wes