The downside is that the first parameter to the function is its namespace. In the above example, it's "main". Note the output:#!/usr/bin/perl use strict; use warnings; my $name = shift; my $func = "update_$name"; main->$func(); # "main" should be the namespace the functions are in. sub update_test { print "!test\n" } sub update_hello { print "hello!\n" }
The (more) normal way to do this is:$ perl x.pl test !test $ perl x.pl hello hello! $ perl x.pl heheh Can't locate object method "update_heheh" via package "main" at x.pl l +ine 10.
Either way, you should check if the function exists before trying to run it, e.g., main->can($func) or exists $updates{$name}.#!/usr/bin/perl use strict; use warnings; my $name = shift; my %updates = ( test => \&update_test, hello => \&update_hello, ); $updates{$name}->(); sub update_test { print "!test\n" } sub update_hello { print "hello!\n" }
In reply to Re: Dynamically Calling a Subroutine
by Tanktalus
in thread Dynamically Calling a Subroutine
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |