gpt4 book ai didi

raku - 如何漂亮地调用名称在字符串中的方法?

转载 作者:行者123 更新时间:2023-12-01 08:56:10 26 4
gpt4 key购买 nike

在 Perl 5 中,我可以说

my $meth = 'halt_and_catch_fire';
my $result = $obj->$meth();

这对于遍历方法名称列表来做事情非常方便。我已经设法弄清楚在 Perl 6 中我 不能 只是说

my $result = $obj.$meth();

确实起作用的一件事是

my $result = $obj.^can($meth)[0]($obj);

但这似乎完全可怕。我该怎么办?

最佳答案

实际上,如果 $meth 包含一个(对一个)可调用对象(例如方法)的引用,那么您可以编写您所写的内容,Rakudo 编译器会接受它:

my $result = $obj.$meth;   # call the Callable in $meth, passing $obj as invocant
my $result = $obj.$meth(); # same

如果 $meth 不是 Callable,Rakudo 会提示(在编译时)。

听起来你想要的是能够只提供方法名称作为字符串。在这种情况下,将该字符串放入 $meth 并写入:

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

更多信息见the Fancy method calls section of the Objects design document .

关于raku - 如何漂亮地调用名称在字符串中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com