function - perl6 如何将用户给出的字符串评估为函数?

标签 function eval raku

我需要根据用户提供的函数生成一些数据点。用户通过 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/

相关文章:

python - 通过Kivy Button调用不同类中的函数

namespaces - clojure - 不同命名空间中的 eval 代码

php - 数组 : set value using dot notation?

c++ - 是否可以声明一个指向具有未知(在编译时)返回类型的函数的指针

c - 可以在函数内部运行一个 c 数组,只用一个指针作为参数吗?

javascript - Node.js TCP 服务器,用于评估和打印数据

raku - 在 raku 中解析参数时删除 = 的使用

perl - 'zef --verbose install Inline::Perl 5' , install fails. I get ' t/p5_object_destructor.t (Wstat: 512 测试: 20 失败: 2)'

string - 如何像 Python 在 Perl 6 中那样对字符串进行切片?

c - 再次出现 undefined reference 错误