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?