Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Re: Building an anonymous subroutine

by mem (Acolyte)
on Aug 12, 2002 at 12:29 UTC ( [id://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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (3)
As of 2024-04-25 17:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found