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

问题描述 投票:6回答:1

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

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

function eval perl6
1个回答
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);
© www.soinside.com 2019 - 2024. All rights reserved.