Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: How do I write subs that take bare blocks as args?

by DamnDirtyApe (Curate)
on Jun 28, 2002 at 06:20 UTC ( #177945=note: print w/ replies, xml ) Need Help??


in reply to How do I write subs that take bare blocks as args?

Thank you both. I've found the relevant sections now in perlsub and in the Camel book. For the record, it was as easy as:

sub each_item (&@) { my $test = shift ; foreach ( @_ ) { return 0 unless ( eval &$test ) } return 1 ; }

Thanks again.

Update: On reading kvale's node a little closer, I tried changing my code to:

sub each_item (&@) { my $test = shift ; foreach ( @_ ) { return 0 unless &{$test} } return 1 ; }

...which also worked. Is there any advantage/disadvantage to this over eval?


_______________
D a m n D i r t y A p e
Home Node | Email


Comment on Re: How do I write subs that take bare blocks as args?
Select or Download Code
Re: Re: How do I write subs that take bare blocks as args?
by educated_foo (Vicar) on Jun 28, 2002 at 06:33 UTC
    ..which also worked. Is there any advantage/disadvantage to this over eval?
    The eval version probably isn't doing what you want, unless you are doing something deliciously perverse. I think your original code is doing this:
    # "$x = eval &$foo" becomes: my $tmp = &$foo(@_); $x = eval $tmp;
    So you're passing @_ to the user's block, then eval'ing the result. This ends up working because the block presumably accesses $_ directly, and returns an integer (which evals as itself). But it's an ... interesting way to get the job done. An optimist would say that the eval version is "very general".

    /s

Re: Re: How do I write subs that take bare blocks as args?
by Courage (Parson) on Jun 28, 2002 at 06:37 UTC
    Among those two calls of &$test they are almost equivalent, and first one will trap any errors, so you can later check $@ variable to see if subroutine died. Like "try" in C++.

    OTOH my personal preference is to call anonymous sub as

    $test->(); $test->('arg1',$arg2);

    Courage, the Cowardly Dog.
    PS. Something fishy is going on there, or my name is Vadim Konovalov. And it's not.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (13)
As of 2014-11-25 21:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (159 votes), past polls