How can I pick up the method whose name is in the string?
In Perl 5, I could say
my $meth = 'halt_and_catch_fire';
my $result = $obj->$meth();
This is great for iterating over a list of method names to do things. I managed to figure out that in Perl 6 I can't just say
my $result = $obj.$meth();
One thing that works is
my $result = $obj.^can($meth)[0]($obj);
But it seems completely awful. How should I do it?
+3
source to share
1 answer
Actually, if $meth
an object (reference to a) contains a callable object such as a method, then you can write what you wrote and the Rakudo Perl 6 compiler will accept it:
my $result = $obj.$meth; # call the Callable in $meth, passing $obj as invocant
my $result = $obj.$meth(); # same
Rakudo will complain (at compile time) if $ meth is not Callable.
It sounds like you just want to specify the method name as a string. In this case, put this line in $ meth and write:
my $result = $obj."$meth"(); # use quotes if $meth is method name as a string
my $result = $obj."$meth"; # SORRY! Rakudo complains if you don't use parens
For more information, see the Fancy method calls the Objects design document .
+8
source to share