As pointed in other answers, the BLOCK as argument to grep is Perl's black magic, but BLOCK as argument to a subroutine prototyped with (&) is just syntactic sugar to allow to omit the sub keyword. So the latter is not "bare BLOCK", but subroutine body, and the return statement returns one frame above, as it should.
More specifically:
An & requires an anonymous subroutine, which, if passed as the first argument, does not require the sub keyword or a subsequent comma.
And:
return
Returns from a subroutine, eval, do FILE, sort block or regex eval block (but not a grep or map block)...
In effect, it's same question, as "Is it possible for a Perl subroutine to force its caller to return?". Following the CPAN links, here's a solution using the Scope::Upper, with a bit convoluted example. Nevertheless, I think it answers your question, i.e. the maybe_working sub doesn't have to take any additional measures for this example to work. The anon sub ALWAYS returns normally, so its the my_grep responsibility to check the return value (so there's reserved return value) and decide, whether to continue or return to 2 stack frames above.
use strict;
use warnings;
use feature 'say';
use Scope::Upper qw/ unwind :words /;
sub my_grep (&@) {
my $code = shift;
my @out;
for ( @_ ) {
say "in @{[ (caller(0))[3] ]}, processing the $_";
my $result = &{ $code };
unwind @out, UP UP if $result eq 'leave';
push @out, $result
}
return @out;
}
sub maybe_working {
my @out = my_grep { return /4/ ? 'leave' : $_ } 1 .. 5;
say 'still here, but you won\'t see this line!';
return @out;
}
say "in final output: $_" for maybe_working;
say 'exiting...';
Output:
in main::my_grep, processing the 1
in main::my_grep, processing the 2
in main::my_grep, processing the 3
in main::my_grep, processing the 4
in final output: 1
in final output: 2
in final output: 3
exiting...
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.