in reply to Re^2: Last undefines a for loop's itererator?
in thread Last undefines a for loop's itererator?

I disagree that my loops aren't equivalent. It is common practice in C to write loops of the form
for( $i = 0; $i <= $foo; $i++ ) { last if bar( $foo ); } if( $i > $foo ) { # Condition never met! }
Essentially, what I would like to do is distinguish between bar(..) being true for the last element in my last, and never being true at all. In "my perfect little world", I would like foreach to unset its iterator variable if and only if it loops through the entire list without encountering last.

So, in my example above, if bar( $foo ) is the first to be true, I want $i == $foo; if bar(..) was never true, it'd be nice to have $i be undef.

In addition, if bar(..) has side effects, then our code is not equivalent.

Edit: Also, I prefer a foreach-style loop because all I'm doing is iterating -- precisely the designated purpose of foreach. Otherwise, if I have a long variable name, I would have to type for( $long_variable_name = 1; $long_variable_name <= 5; $long_variable_name ++ ) versus for $long_variable_name ( 1 .. 5 ). I'm pretty sure I'm not the only one who has made copy-paste errors like for( $j = 0; $j <= 5; $i++ ).

Replies are listed 'Best First'.
Re^4: Last undefines a for loop's itererator?
by Aristotle (Chancellor) on Nov 14, 2005 at 00:22 UTC

    I would like foreach to unset its iterator variable if and only if it loops through the entire list without encountering last.

    It doesn’t unset the iterator, it restores it. But people already get bitten by retained values of $1 and friends when a pattern with capturing parens failed to match. Do you really want to perpetuate this pattern into such a common construct as foreach?

    If you want to retain the value, save it. It’s not hard, it makes it explicit what’s going on, and it lets foreach follow consistent mechanics with fewer surprises.

    Makeshifts last the longest.