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

Answer: calling a sub using its name assigned to a variable ?

( #276449=categorized answer: print w/ replies, xml ) Need Help??

Q&A > subroutines > calling a sub using its name assigned to a variable ? contributed by jryan

As NetWallah notes, you want to use a dispatch table, as it allows you to check for the existance of the sub before you call it (one of the "various valid reasons relating to maintainability and security"). However, there is no need to have to deal with such annoying syntax. Check out Exporter::Dispatch on the CPAN. It will make your life much easier. For instance, NetWallah's sample now becomes even cleaner. First the table definition: (with the prototypes removed, as they are pointless in this situation)

package Options; use Exporter::Dispatch; sub main_menu { ... } sub other_menu { ... }

And then the call (with the addition of an existance check):

my $var = ...; my %dispatch_sub = create_dptable Options; $dispatch_sub{$var}->($screenpos1, $screenpos2) if exists $dispatch_su +b{$var};

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2016-06-25 08:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...











    Results (323 votes). Check out past polls.