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

Re: Dynamically Calling a Subroutine

by Somni (Friar)
on Jul 13, 2011 at 17:49 UTC ( #914175=note: print w/replies, xml ) Need Help??

in reply to Dynamically Calling a Subroutine

Typically, I'll revert to a dispatch table for this sort of task:
my %dispatch = ( test => sub { print "test\n" }, hello => sub { print "hello\n" }, ); my $name = 'test'; $dispatch{$name}->(); $name = 'hello'; $dispatch{$name}->();
This has the benefit of confining your subroutines to a very small namespace, as opposed to the entire symbol table. You can validate your input (lookup the key before calling it), and thereby provide better diagnostics.

In the event I actually want the symbol table (I can't actually recall wanting this, outside of calling methods...) then I tend to prefer can(). It does have caveats: if you're dealing with a class, it will search up the inheritance tree. However, this is usually something I want.

my $name = 'test'; __PACKAGE__->can("update_$name")->(); $name = 'hello'; __PACKAGE__->can("update_$name")->(); sub update_test { print "test\n" } sub update_hello { print "hello\n" }
You can similarly check for the function before simply calling it, by checking the return value of can(), which is a subref.

Replies are listed 'Best First'.
Re^2: Dynamically Calling a Subroutine
by 7stud (Deacon) on Jul 14, 2011 at 22:48 UTC
    I can't find any documentation for the can() function. Link?

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://914175]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2023-11-30 07:32 GMT
Find Nodes?
    Voting Booth?

    No recent polls found