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

is there a way to use the value of a variable directly as a function? sort of like this: $var = "funcname"; $var(); sub funcname{ }

Replies are listed 'Best First'.
Re: using variables as functions
by takshaka (Friar) on May 13, 2000 at 21:23 UTC

    perlmonkey forgot to mention a reference to a named subroutine:

    my $var = \&funcname; &$var; sub funcname { print "funcname\n" }
    This is preferable to storing the subroutine name in a variable (symbolic reference):
    $var = 'funcname'; &$var;
    If you think you need the above construct, you are probably mistaken. Symbolic references are namespace hoodoo and should be avoided unless you know what you are getting into (which is why 'use strict' complains). If you need to store function names in a variable, use a lookup hash with hard references.
    my %dispatch = (foo => \&foo, bar => \&bar ); foreach my $func (keys %dispatch) { &{ $dispatch{$func} }; } sub foo { print "foo\n"; } sub bar { print "bar\n"; }
    perlman:perlref describes references in detail. The 5.6.0 perlfaq7 also has a bunch of information about this under the question "How can I use a variable as a variable name?"

    Update: There's also this thread.

Re: using variables as functions
by perlmonkey (Hermit) on May 13, 2000 at 20:49 UTC
    There are three ways that I know of to call a sub as a variable. You can store a pointer to an anonymous function in a variable and call that, but I dont think this is what you are looking for. You can also store the proper function name in a variable can call it by just prepending a '&' on the front like
    $var = 'funcname'; &$var(); sub funcname { print "Hello\n" }
    But this will not work if you are using 'strict', so here are the three ways you can do it that will work with strict.
    use strict; # # create an anonymous function # my $func = sub { print "Sub Anonymous\n" }; # # create named sub # sub funcname { print "Sub funcname\n" } # # call anonymous subroutine # &$func(); my $mysub = 'funcname'; # # call subroutine but only with no strict references # no strict 'refs'; &$mysub(); use strict; # # or call with eval statement # eval('&'.$mysub.'()'); # # catch error from eval statement # if( $@ ) { warn($@); }
    The first one is just an anonymous subroutine, and the next two are calling a name subroutine referenced in a variable. By turning off 'strict refs' you run the risk of getting a crtitical run time error if there is no function named in $mysub. So it is probably better to use the eval and catch the error. That will prevent the program from critically failing if the function does not exist.
Re: using variables as functions
by mdillon (Priest) on May 14, 2000 at 00:40 UTC
    just for the sake of completeness, i'd like to add that you could also use the following notation for takshaka's solution:
    my $var = \&funcname; $var->();