Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Re: Building an anonymous subroutine

by mem (Acolyte)
on Aug 12, 2002 at 12:29 UTC ( #189457=note: print w/ replies, xml ) Need Help??


in reply to Re: Building an anonymous subroutine
in thread Building an anonymous subroutine

Instead of returning subs which constantly evals strings (your eval $evalN lines), you can just eval a string that defines a sub once, something like this:

#!/usr/bin/perl -l use strict; use warnings; my @subs = ( q/ { my $i=0; sub { print "($i) First sub, sir!"; ++$i; } } /, q/ { my $i=0; sub { print "($i) Another sub, sir!"; ++$i; } } / ); my @code = map { eval $_ } @subs; $code[rand(2)]->() for (0 .. 20);

I hope that isn't too obscure. It just places two strings into an array. Each string is a block of code defining a variable and returning a sub using that variable. Later the strings are eval'ed in order to generate callable code. And last, the code is actually called. The random index is there just to make it clear that there is a closure in the game.

Sorry about that "sir!" thing, I saw Full Metal Jacket the other day and I can't get it out of my head. Be happy that my subs aren't mooing.


Comment on Re: Re: Building an anonymous subroutine
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-09-19 22:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (147 votes), past polls