in reply to Dynamically Calling a Subroutine
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.my %dispatch = ( test => sub { print "test\n" }, hello => sub { print "hello\n" }, ); my $name = 'test'; $dispatch{$name}->(); $name = 'hello'; $dispatch{$name}->();
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.
You can similarly check for the function before simply calling it, by checking the return value of can(), which is a subref.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" }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Dynamically Calling a Subroutine
by 7stud (Deacon) on Jul 14, 2011 at 22:48 UTC | |
by Somni (Friar) on Jul 14, 2011 at 23:19 UTC |