1

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.

  • (1) it should work (2) it is a serious security concern to `eval` data coming from outside your code. – GMB Dec 06 '22 at 23:28
  • 2
    It doesn't work because division by zero; try inspecting the value of `$@`. You could try adding quotes around the variable, e.g. `eval("\"$x\"")`. – Nathan Mills Dec 06 '22 at 23:51
  • My thanks to you both. – Quandale Dingle Dec 07 '22 at 00:19
  • 1
    `$ENV{SOMETHING}/dir/$ENV{SOMETHING_ELSE}` is not valid Perl code. (Well, it is, but it's a pair of divisions.) – ikegami Dec 07 '22 at 06:21
  • If this is some way to read settings from a file, there are probably better ways of doing it. If you include a description of what you are trying to do, someone might be able to advice you. – TLP Dec 07 '22 at 10:41

1 Answers1

3

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.

zdim
  • 64,580
  • 5
  • 52
  • 81