Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Building an anonymous subroutine

by Basilides (Friar)
on Aug 12, 2002 at 10:07 UTC ( [id://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!

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://189428]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-26 00:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found