Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
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};

Comment on Answer: calling a sub using its name assigned to a variable ?
Select or Download Code
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 chilling in the Monastery: (10)
As of 2014-12-18 22:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (67 votes), past polls