Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2018-03-18 15:55 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (230 votes). Check out past polls.