perl6如何评估用户给定的字符串作为函数?

lis*_*tor 6 eval function perl6

我需要根据用户提供的功能生成许多数据点。用户通过提示输入功能(“输入功能:”);我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

另外,我在使用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
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的任何建议 !!!

uge*_*exe 6

这些是编译时错误-&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);
Run Code Online (Sandbox Code Playgroud)