Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Building an anonymous subroutine

by Basilides (Friar)
on Aug 12, 2002 at 10:07 UTC ( #189428=note: print w/ replies, xml ) Need Help??


in reply to Building an anonymous subroutine

Perhaps you could put your common code in strings and use eval statements to reference it:

$encode = 'p'; $sub_ref = test($encode); sub test { my $e = shift; my $eval1 = 'print "first bit of reusable code\n";'; my $eval2 = 'print "second bit of reusable code\n";'; $e eq 'p'? return sub { eval $eval1; print "you typed 'p' as your option\n"; eval $eval2; }: $e eq 'b'? return sub { eval $eval1; print "you typed 'b' as your option\n"; eval $eval2; }: return sub { eval $eval1; print "you typed 'u' as your option\n"; eval $eval2; }; } $encoded_output = &$sub_ref;
Sorry this is such a cruddy example!


Comment on Re: Building an anonymous subroutine
Select or Download Code
Re: Re: Building an anonymous subroutine
by mem (Acolyte) on Aug 12, 2002 at 12:29 UTC

    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.

Re: Re: Building an anonymous subroutine
by Anonymous Monk on Aug 13, 2002 at 00:37 UTC
    Doing an eval without checking $@ and throwing a useful error message is a really bad idea. I would also suggest reading the section on Plain Old Comments in perlsyn and using that to cause any errors thrown from within the subroutine to have more useful and meaningful names than just eval 38.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2014-12-21 02:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (102 votes), past polls