http://www.perlmonks.org?node_id=903125


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.