Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: using variables as functions

by perlmonkey (Hermit)
on May 13, 2000 at 20:49 UTC ( [id://11427]=note: print w/replies, xml ) Need Help??


in reply to using variables as functions

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2024-04-24 23:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found