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

I want to still use foreach

Why? A C-style for is perfectly acceptable here. That is, so long as you use it correctly. For the example you gave to match your foreach loop, you'd have to change your condition to $i < $foo because your current code, $i <= $foo, will leave you with $i being one more than $foo if you get to the end of your loop.

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^3: Last undefines a for loop's itererator?
by kaif (Friar) on Nov 13, 2005 at 23:23 UTC
    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++ ).

      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.