Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: make subroutine that takes expression as implicit block as first arg

by kennethk (Abbot)
on Aug 13, 2010 at 19:46 UTC ( [id://854995]=note: print w/replies, xml ) Need Help??


in reply to make subroutine that takes expression as implicit block as first arg

You can accomplish your task using Prototypes. In fact, from the linked documentation,
here's a reimplementation of the Perl grep operator:

sub mygrep (&@) { my $code = shift; my @result; foreach $_ (@_) { push(@result, $_) if &$code; } @result; }

Update: Your example would be called as: print join ",", mygrep {$_ % 2 == 0} 0..10; Note the deviation from the proposed use case. I'd initially missed the spec for "automatically put [ting] it in an implicit block"

Replies are listed 'Best First'.
Re^2: make subroutine that takes expression as implicit block as first arg
by oko1 (Deacon) on Aug 13, 2010 at 19:54 UTC

    That won't work, for the proposed case:

    Type of arg 1 to main::mygrep must be block or sub {} (not numeric eq +(==)) at /tmp/mygrep line 7, near "10)" Execution of /tmp/mygrep aborted due to compilation errors.

    Perhaps something like this?

    sub mygrep { my $s = "grep $_[0]"; eval $s; } print for mygrep('$_ % 2 == 0, 0..10'); # :-)

    --
    "Language shapes the way we think, and determines what we can think about."
    -- B. L. Whorf
      I added a use case, as this sort of structure is a bit sensitive - perl apparently interprets the OP proposed use case as an anonymous hash because parentheses are present.

      When I was going through a clever phase, I played a bit with prototypes, and decided they are generally more trouble than they are worth. IMHO, of course.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-20 09:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found