Search code examples
stringrakusubroutine

How to call a sub from a variable with the name of the sub?


Given the following code:

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

How do I call the sub foo using $call_me?


Solution

  • 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.