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
&$perl_function_name();

## calling with parameter passing
&$perl_function_name(10);

## example function
sub call_function{
my $param = shift;
if($param){
print "Calling function using variable with parameter $param\n";
}
else{
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




5 comments:

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";
$obj->$name(...);
}