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.$var = 'funcname'; &$var(); sub funcname { print "Hello\n" }
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.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($@); }
In reply to Re: using variables as functions
by perlmonkey
in thread using variables as functions
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |