Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
We don't bite newbies here... much
 
PerlMonks  

Re: Re: Building an anonymous subroutine

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

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.