damlit
damlit

Reputation: 145

How to call method by Name from variable value in perl?

I have name of method which I have to call (from another script btw) from arguments - as a variable. In a big simplify:

$method1 = "hello()";

And I have to write:

hello();

but I don't know what name is in #method1.

How can I do this?

Upvotes: 2

Views: 1368

Answers (1)

amon
amon

Reputation: 57600

This is not really recommended because there are safety issues, but you can use the name of a subroutine to call it:

my $method = "hello";
{
  no strict 'refs';
  &{$method}();  # same as hello()
}

This &{...}() syntax “dereferences” the subroutine name and calls it.

If you're calling methods on an object, you can skip the no strict 'refs' part:

my $method = 'name';
$object->$method();  # same as $object->name

If you only want to allow a couple of subroutines, it would be much better to store them in a hash table:

my %known_functions = (
  hello => \&hello,  # \& stores a reference to a subroutine 
  bye => \&not_hello,  # added benefit: renaming them
);

# define the functions somewhere
sub hello { ... }
sub not_hello { ... }

# can't access secret methods unless they are added to the hash table
sub secret { ... }

# use a hash lookup and call the method
my $method = 'hello';
$known_functions{$method}();

Upvotes: 5

Related Questions