Tuesday, May 20, 2008

Perl: Call function using a variable

Share at Facebook

You can call a Perl function using a variable. For example below code, here the variable $perl_function_name whose value is "call_function", you can call the function as &$perl_function_name() instead of calling call_function();

my $perl_function_name = "call_function";

## calling without parameter passing

## calling with parameter passing

## example function
sub call_function{
my $param = shift;
print "Calling function using variable with parameter $param\n";
print "Calling function using variable\n";
Using the 'use strict;' I found the code doesn't work. The error i got Can't use string ("call_function") as a subroutine ref while "strict refs" in use Anyone knows why? Or any other way to do this?

For more Perl you can take a look at here http://icfun.blogspot.com/search/label/perl


Nick said...

You can get use strict by doing:

use strict;
no strict "refs";

Check out the docs, though, as this does have other effects.

David said...

Another option is to use eval

eval{ &$perl_function_name(10)} ;

This will work only in run time, and you wouldn't need to use

no strict "refs";

Anonymous said...

how to do this when calling a function on an object ?

Jon Hermansen said...

I'm also interested to know how to accomplish this when calling a function of an object.

Ninuzzo said...

Methods are called the same way: $obj->$name(...). Using eval with braces does not work. The safest and most efficient way is to scope the no strict "refs" to the call only:

no strict "refs";