routine EVAL

Documentation for routine EVAL assembled from the following types:

class Cool

From Cool

(Cool) routine EVAL

Defined as:

method EVAL(*%_)

It calls the subroutine form with the invocant as the first argument, $code, passing along named args, if any.

language documentation Independent routines

From Independent routines

(Independent routines) routine EVAL

Defined as:

proto sub EVAL($code where Blob|Cool|CallableStr() :$lang = 'perl6',
                PseudoStash :$context*%n)
multi sub EVAL($codeStr :$lang where { ($lang // ''eq 'Perl5' },
                PseudoStash :$context)

This routine coerces Cool $code to Str. If $code is a Blob, it'll be processed using the same encoding as the $lang compiler would: for perl6 $lang, uses utf-8; for Perl5, processes using the same rules as perl.

This works as-is with a literal string parameter. More complex input, such as a variable or string with embedded code, is illegal by default. This can be overridden in any of several ways:

use MONKEY-SEE-NO-EVAL# Or... 
use MONKEY;             # shortcut that turns on all MONKEY pragmas 
use Test;
 
# any of the above allows: 
EVAL "say { 5 + 5 }";   # OUTPUT: «10␤»

In case the MONKEY-SEE-NO-EVAL pragma is not activated, the compiler will complain with a EVAL is a very dangerous function!!! exception. And it is essentially right, since that will run arbitrary code with the same permissions as the program. You should take care of cleaning the code that is going to pass through EVAL if you activate the MONKEY-SEE-NO-EVAL pragma.

Please note that you can interpolate to create routine names using quotation, as can be seen in this example or other ways to interpolate to create identifier names. This only works, however, for already declared functions and other objects and is thus safer to use.

Symbols in the current lexical scope are visible to code in an EVAL.

my $answer = 42;
EVAL 'say $answer;';    # OUTPUT: «42␤»

However, since the set of symbols in a lexical scope is immutable after compile time, an EVAL can never introduce symbols into the surrounding scope.

EVAL 'my $lives = 9'say $lives;   # error, $lives not declared 

Furthermore, the EVAL is evaluated in the current package:

module M {
    EVAL 'our $answer = 42'
}
say $M::answer;         # OUTPUT: «42␤»

And also in the current language, meaning any added syntax is available:

sub infix:<mean>(*@ais assoc<list> {
    @a.sum / @a.elems
}
EVAL 'say 2 mean 6 mean 4';     # OUTPUT: «4␤»

An EVAL statement evaluates to the result of the last statement:

sub infix:<mean>(*@ais assoc<list> {
    @a.sum / @a.elems
}
say EVAL 'say 1; 2 mean 6 mean 4';         # OUTPUT: «1␤4␤» 

EVAL is also a gateway for executing code in other languages:

EVAL "use v5.20; say 'Hello from perl5!'":lang<Perl5>;

You need to have Inline::Perl5 for this to work correctly.