Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Bare BLOCK vrs. grep BLOCK

by vr (Curate)
on Jan 16, 2018 at 17:52 UTC ( [id://1207363]=note: print w/replies, xml ) Need Help??


in reply to Bare BLOCK vrs. grep BLOCK

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...

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1207363]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (6)
As of 2024-03-29 09:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found