Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: execute function with name passed as string parameter

by shmem (Canon)
on May 05, 2011 at 12:05 UTC ( #903125=note: print w/ replies, xml ) Need Help??


in reply to execute function with name passed as string parameter

What the other monks said, but TIMTOWTDI. You can also store subroutine references in your hash and execute them.

perl -le '$choice='1'; %hash=( '0' => \&one, '1' => \&two ); $hash{$ch +oice}->(); sub one {print "one"}; sub two {print "two"}'

You could also call the subroutine reference via &{$hash{choice}} - but be aware that there's a subtle difference:

$\="\n"; # output record separator $choice='1'; %hash=( '0' => \&one, '1' => \&two ); @_ = "fish"; $hash{$choice}->(); &{$hash{$choice}}; one; &one; sub one { print "one", @_ } sub two { print "two", @_ } __END__ two twofish one onefish

That is, &sub, &$sub, &{gimme_a_subref()} and so on - without parens - pass the current @_ to the called subroutine. Of course, &{$hash{$choice}}() - with parens - passes an empty list.


Comment on Re: execute function with name passed as string parameter
Select or Download Code
Re^2: execute function with name passed as string parameter
by rgcosma (Beadle) on May 05, 2011 at 14:30 UTC
    OK, so it was a syntax misunderstanding, thank you all.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (12)
As of 2014-07-29 12:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (217 votes), past polls