I ran into this while debugging a fellow programmers code. Took a bit to realize the problem and was wondering if this is an expected situation...
When calling a subroutine/function from within a loop, if we call 'next' within that function (outside of a looping construct itself), it actually iterates the loop of the calling scope rather than issuing an error. Code example:
use strict; my @stuff = (1, 2, 3, 4, 5); foreach my $s (@stuff) { test($s); print "past\n"; } sub test { my ( $s ) = @_; if ($s == 3) { next; #note that this is not within a loop in the #scope of the subroutine } else { print $s . "\n"; } }
What I would expect is that I get a compile time error similar to if I attempted to call next outside a loop. Instead what I get is:
1 past 2 past 4 past 5 past
This shows that the subroutine is actually iterating the last loop, independent of the scope.
My opinion is on the fence on whether I like this result or not...but I do find it unexpected. I assumed that the actions within a subroutine is in its own scope and would not be able to affect the outer loop of a calling scope.
The functionality makes it seem as if the batch of the sub is 'imported' into the process, retaining the scope of the batch for variables but not for things like looping constructs.
Thoughts?
Thanks,In reply to Loop controls transcends scope? by smsiebe
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |