The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

Synopsis:

eval[@$][?] [Perl-code]

Run Perl-code in the context of the current frame.

If no string is given after the command "eval", we run the string from the current source code about to be run. If the command ends ? (via an alias) and no string is given we will the perform the translations:

{if|elsif|unless} (expr) [{]  => expr
{until|while} (expr) [{]      => expr
return expr [;]               => expr
{my|local|our} (expr1, expr2) = (v1,v2);
                              => (expr1, expr2) = (v1,v2)
{my|local|our} var = expr ;   => expr
given expr                    => expr
sub fn(params)                => (params)
var = expr                    => expr

The above is done via regular expression. No fancy parsing is done, say, to look to see if expr is split across a line or whether var an assigment might have multiple variables on the left-hand side.

The value of the expression is stored into global array @DB:D so it may be used again easily.

Normally eval assumes you are typing a statement, not an expression; the result is a scalar value. However you can force the type of the result by adding the appropriate sigil @, %, or $.

Examples:

eval 1+2 # 3
eval$ 3   # Same as above, but the return type is explicit
$ 3       # Probably same as above if $ alias is around
eval $^X  # Possibly /usr/bin/perl
eval      # Run current source-code line
eval?     # but strips off leading 'if', 'while', ..
          # from command
eval@ @ARGV  # Make sure the result printed and saved as an array rather
             # than as an array converted to a scalar.
@ @ARG       # Same as above if @ alias is around
eval% %ENV   # Make sure the result printed/saved as a hash
use English  # Note this is a statement, not an expression
use English; # Same as above
eval$ use English # Error because this is not a valid expression

See also:

set auto eval, set display eval, and shell.