Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

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

by jryan (Vicar)
on Jul 21, 2003 at 20:38 UTC ( #276449=categorized answer: print w/replies, xml ) Need Help??

Q&A > subroutines > calling a sub using its name assigned to a variable ? - Answer 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?
[choroba]: So an old friend is back...
[choroba]: he just forgot his password, it seems.
[Your Mother]: Still… Old… Friend…!
[Your Mother]: Is your guess as good as mine?
choroba winks.

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2017-02-28 02:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?






    Results (394 votes). Check out past polls.