Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: executing subroutines via variable

by Kanji (Parson)
on Nov 19, 2002 at 17:16 UTC ( [id://214192]=note: print w/replies, xml ) Need Help??


in reply to executing subroutines via variable

Although it's tempting to use eval in a situation like this, I prefer (ab)using coderefs, either by employing a hash of anonymous subs (rather than subs proper)...

package atm; my %code = ( var1 => sub { print 1 }, var2 => sub { print 2 }, # ... varN => sub { print N }, ); package main; if ( exists $atm::code{$varN} ) { $atm::code{$varN}->( object_vars($var1) ); } else { # no matching sub }

... or testing for the existance of the sub you want to run with can, and executing the coderef it returns.

if ( my $sub = atm->can($varN) ) { $sub->( object_vars($varN) ); } else { # no matching sub }

    --k.


Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-19 12:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found