huanghongqiao
huanghongqiao

Reputation: 13

why Perl eval get errors

If I write this code:

for $i (1..3) { 
 $j = $i;
print $j;
}  

it works.

And this code will work:

$code = "  
 for $i (1..3) { 
  #### $j = $i;
  print $j;
}  
eval $code  

But if I try to write it like this:

$code = "
for $i (1..3) { 
$j = $i;
print $j;
 }  
eval $code  

It will catch an error, why? who can help me?

Upvotes: 1

Views: 123

Answers (2)

Gilles Quénot
Gilles Quénot

Reputation: 185075

You are missing a quote :

$code = '
for $i (1..3) { 
    $j = $i;
    print $j;
}';
eval $code;

and 'single quotes' here are mandatory to not expand variables before the eval call.

Upvotes: 3

hobbs
hobbs

Reputation: 239871

The second one works purely by accident. Your double-quoted string is interpolating empty values for $i and $j and you're actually running

for  (1..3) {
  ### = 
  print ;
}

which coincidentally works because for will assign to $_ if you don't name a variable, and print will print $_ by default. When you remove the comment marker, the lone equals sign causes a syntax error.

If you had used strict it would have prevented you from compiling the broken code in the first place, and if you had used warnings it would have at least warned you about the use of the uninitialized variables $i and $j in string interpolation.

Upvotes: 9

Related Questions