stringperlevalevaluate

Evaluate a string read from a file in perl


Made up example (perl):

my $x = read_input_from_file();

# $x now contains string $ENV{SOMETHING}/dir/$ENV{SOMETHING_ELSE}
my $y = eval($x);  # doesnt work

How can I get value of string contained in $x in the script?

So far I have tried using eval which doesn't generate any output. I am hoping that something already exists in perl and these string expressions do not need to be parsed and evaluated.


Solution

  • The "string" eval is a little specific:

    eval in all its forms is used to execute a little Perl program.
    ...
    In a string eval, the value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program.

    So this evaluates code, and with a variable to be evaluated containing a string literal we have a "bareword" ("Unquoted string") which is generally no good. In your case, those / in $x cause additional trouble.

    If the content of the variable to evaluate is a string literal (not code) it need be quoted

    my $y = eval q(") . $x . q(");  # double-quote so that it interpolates
    

    I use the operator form of a single quote, q(). Quoted under it is a double-quote since $x itself seems to contain variables that need be evaluated (interpolated). Another way is to form and quote the string directly, by using the operator form for double-quotes, qq("$x").

    Keep in mind that running code from external sources can be a serious security problem.