Home > database >  How to convert a string to a sub?
How to convert a string to a sub?

Time:07-25

Given the following code:

sub foo {
    say 'Hello';
}
my $call_me = 'foo';

How do I call the sub foo using $call_me?

CodePudding user response:

Use:

::( "&" ~ $call_me )()

:: accesses the symbol table in the current package; subs are stored in that symbol table with the sigil & which is why we have to concatenate (~) the name with that to go from string to the function; that symbol table maps identifiers to the actual function.

For methods, this is easier:

my $method-name = "foo";
$object."$method-name"();

Note that you can create a name inside the "" there, it doesn't have to be just a variable name.

Also note that the () are required in that case.

  • Related