Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://189457]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2018-04-24 07:39 GMT
Find Nodes?
    Voting Booth?