It has always seemed weird to me to write code like
my $iold;
for my $i ( 1 .. $foo ) {
if( bar($i) ) {
$iold = $i;
last;
}
}
Doesn't it just seem like a waste of variables? You're clearly using $i and $iold for the same purpose.
No, you're using $i as a loop variable and $iold as the return value of the loop. Variables are cheap. Using them to buy clarity is a "good deal"™.
As for why it isn't a subroutine, perhaps because I like this code all in one place. Shrug.
This code is all in one place. It is just a loop with a return value. Read carefully.
my $iold = sub { for my $i ( 1 .. $foo ) { if( bar($i) ) { return($i); } } }->(); # calls this anonymous sub (setting $iold)
Note that it takes the same number of lines to set an external (to the loop) value and last; as it does to define your loop as an anonymous sub and return($i);
This also gets you the benefit that if the loop gets more complicated or needs to be reuse, refactoring just means yanking it verbatim and making it a named sub because nothing inside of it relies on lexical scope. (Yeah, you have to put any parameters in the ->($var1, $var2); part for this to scale.)
In reply to Re^4: no chunk is too small
by ewilhelm
in thread Last undefines a for loop's itererator?
by BUU
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |