Given the following code:
sub foo {
say 'Hello';
}
my $call_me = 'foo';
How do I call the sub foo
using $call_me
?
Given the following code:
sub foo {
say 'Hello';
}
my $call_me = 'foo';
How do I call the sub foo
using $call_me
?
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.
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 &::($name)
instead of ::("&" ~ $name)
–
Mingo © 2022 - 2024 — McMap. All rights reserved.