我需要根据用户提供的函数生成一些数据点。用户通过 prompt("Enter function:");我正在尝试使用 EVAL,但我不断收到错误消息。最好的方法是什么?谢谢 !!!
> my $k = prompt("Enter function: ");
Enter function: sub x($a) { say $a * 2; };
> $k
sub x($a) { say $a * 2; };
> use MONKEY-SEE-NO-EVAL
Nil
> use Test
Nil
> EVAL $k
&x
> say x(4)
===SORRY!=== Error while compiling:
Undeclared routine:
x used at line 1
另外,我在使用 Q:f 插入函数时也遇到了一些麻烦。
> Q:f { sub x($a) { say $a * 2; }; }
sub x($a) { say $a * 2; };
> &x
===SORRY!=== Error while compiling:
Undeclared routine:
x used at line 1
在此先感谢您的任何建议 !!!
最佳答案
这些是编译时错误——&x 在编译时不存在。相反,您应该 EVAL
将您的例程转换为您在编译时知道的名称(在本例中为 &my-x
):
use MONKEY-SEE-NO-EVAL;
my $string = q|sub x($a) { say $a * 2; };|;
my &my-x = EVAL $string;
my-x(1);
关于function - perl6 如何将用户给出的字符串评估为函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327156/