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

1

6

Given the following code:

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

How do I call the sub foo using $call_me?

Sunil answered 24/7, 2022 at 1:26 Comment(0)
F
9

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.

Flinty answered 24/7, 2022 at 7:42 Comment(6)
Thank you, especially for the explanation!Sunil
You'll have to thank @elizabeth-mattijsen too :-)Flinty
Great answer! I just note a couple of variations (i) my $c = '&foo'; ::(~$c)() embed the & in the name and uses str concat (~) as prefix to coerce $c to Str or (ii) my $d = 'foo''; ::("&$d")() use double quotes to interpolate the (&) onto the front.Crooks
You should use &::($name) instead of ::("&" ~ $name)Mingo
@Mingo any reason? Is it just more idiomatic?Flinty
@Flinty it will at least save on a string-concat (creating a new short-lived temporary string) etc...Interplead

© 2022 - 2024 — McMap. All rights reserved.