amnesty_puppy has asked for the wisdom of the Perl Monks concerning the following question:

I'm not sure how to do this, but I want to call a subroutine from a module where the name of the subroutine is in a variable, such as @{$array_name} for arrays. I guessed at &Modname::{$subname} but just got a syntax error. Tried a bunch of combinations of characters but to no avail, alternatively, am I taking completely the wrong approach?
Thanks, Dom.

Replies are listed 'Best First'.
Re: Module suboutine needs dereferencing?
by Errto (Vicar) on Feb 03, 2005 at 21:00 UTC

    This can be done through symbolic references. If the module name is a literal and the subroutine name is a variable, then you can use

    &{"Modname::$subname"}
    to access the subroutine. And make sure that when calling this subroutine you put parentheses around the arguements as well. Also note that you cannot do this if use strict 'refs' is in effect.

    Personally, I would avoid using symbolic references if I could help it and just stick with using real references. For example you could create a hash of subroutine references:

    my %table = (name1 => \&subname1, name2 => \&subname2 ... );
    and then call it with
    $table{$name}->( ... args ... )

Re: Module suboutine needs dereferencing?
by TedYoung (Deacon) on Feb 03, 2005 at 20:56 UTC

    Hi,

    Well, you have a couple of options depending on what you want to do:

    $subname = 'foo'; # Same as Modname->foo(@params); Modname->$subname(@params); # Same as Modname::foo(@params); "Modname::$subname"->(@params);

    PS: one other note, if you can use subreferences ($sub = \ &Modname::foo), that tends to be a little safer. Just make sure that you are not using a variable that came from a user/webform/file without checking it first.

    Ted Young

    ($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)