Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl6 How to EVAL a string given by user to be a function?

I need to generate a number of data points according to functions supplied by users. Users enter the function via prompt("Enter function: "); I am trying to use EVAL, but I keep getting errors. What is the best approach? Thanks !!!

> 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

Also, I have some trouble with the Q:f to interpolate a function as well.

> 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

Thanks in advance for any suggestions !!!

like image 358
lisprogtor Avatar asked Mar 24 '19 18:03

lisprogtor


1 Answers

Those are compile time errors -- &x doesn't exist at compile time. Instead you should EVAL your routine into a name you do know at compile time (in this case &my-x):

use MONKEY-SEE-NO-EVAL;
my $string = q|sub x($a) { say $a * 2; };|;
my &my-x = EVAL $string;
my-x(1);
like image 174
ugexe Avatar answered Nov 15 '22 09:11

ugexe