Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2016-10-24 00:38 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (302 votes). Check out past polls.