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

Re: Dynamically Calling a Subroutine

by Somni (Friar)
on Jul 13, 2011 at 17:49 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-25 22:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found