Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Dynamically Calling a Subroutine

by Tanktalus (Canon)
on Jul 13, 2011 at 00:00 UTC ( [id://914038]=note: print w/replies, xml ) Need Help??


in reply to Dynamically Calling a Subroutine

#!/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 downside is that the first parameter to the function is its namespace. In the above example, it's "main". Note the output:
$ 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.
The (more) normal way to do this is:
#!/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" }
Either way, you should check if the function exists before trying to run it, e.g., main->can($func) or exists $updates{$name}.

Replies are listed 'Best First'.
Re^2: Dynamically Calling a Subroutine
by bichonfrise74 (Vicar) on Jul 13, 2011 at 05:37 UTC
    Wow. I have forgotten this already.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (6)
As of 2024-04-19 06:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found