My question is: why this behaviour ?
I believe that's it's implemented at its simplest. next, last and redo simply locate the closest frame on the stack that supports the operation. Doing anything different would require extra work.
| [reply] [d/l] [select] |
why this behaviour ? what is the logic behind it ? wouldn't it be beneficial if the interpreter threw a error for invalid use of next, in this case ?
It's something you shouldn't do without a good reason, hence the warning, but why do you want it to throw an error by default?
In any case, you can use warnings 'all', 'FATAL' => 'exiting'; if that's to your liking.
| [reply] [d/l] |
I'm not sure, but pg's comment in the referenced thread talks about how semantically a sub is a block in the scope of where it was called (with differences of course, such as not seeing lexicals of the containing scope). Since next just looks up the scope change for the nearest encasing block, which in this case is the foreach.
I don't really know how to explain the quoted documentation though. I just edited your function to include a return statement, and it still worked the same way.
| [reply] |
I don't really know how to explain ["next" cannot be used to exit a block which returns a value such as "eval {}", "sub {}" or "do {}"...]
It means next, last and redo ignore do blocks, eval blocks, etc. They will only cause loop blocks and bare blocks to repeat, exit, etc. It makes more sense when you read that same line in the documentation for last, since next doesn't cause a loop to exit.
foreach my $var (1, 2, 3, "skip", 4) {
eval { # This block is ignored.
if ($var eq "skip") {
next;
}
};
print $var;
}
print("\n");
foreach my $var (1, 2, 3, "skip", 4) {
{ # This block exits.
if ($var eq "skip") {
next;
}
}
print $var;
}
print("\n");
outputs
1234
123skip4
| [reply] [d/l] [select] |
Ah, that makes sense. Thanks!
| [reply] |
I don't really know how to explain the quoted documentation though. I just edited your function to include a return statement, and it still worked the same way.
The (poorly worded) documentation doesn't mean next won't leave that scope - it just means you can't use next to resume execution just after of the current eval {}, etc. when there's no loop in the eval {}, etc.
| [reply] |