Implementing Perl6 eval($str, :lang)
Moritz++ helped me implement a proof of concept eval-perl5 that works in rakudo, and uses Perlito5 (a perl5 compiler written in perl5).
This snippet could be used to implement a perl5 compatibility layer that works both in rakudo and niecza (and maybe pugs).
Perlito5 -Cperl6 is invoked using shell(). It compiles the string to perl6, and the result is eval'ed using plain perl6 Str.eval():
multi eval($str, :$lang! where 'perl5') {
my $inp_file = "tmp.p5";
my $out_file = "tmp.p6";
my $fh = open($inp_file, :w);
$fh.print($str);
$fh.close;
shell "perl perlito5.pl -Isrc5/lib -Cperl6 $inp_file > $out_file";
my $p6_str = slurp $out_file;
$p6_str.eval;
}
the new eval() can be used like this:
my $p5_str = ' my @x; $x[1] = 2+2; say "got $x[1]"; '; eval($p5_str, :lang);
Perl5-to-perl6 is a work in progress. Once Perlito5 is bootstrapped in perl6, we can create a plain perl6 module instead of invoking the shell.
Moritz also noted that the eval'ed code could be given access the perl6 lexical scope using perl6 CALLER. The lexical lookup will probably be provided by the perl5-to-perl6 compiler automatically.
The code is in github and was tested with latest rakudo-star and perlito5.
Leave a comment