Code:
my $tmp='x $i y'; # define a macro or whatever
for my $i (0..5){
my $var;
# eval { $var=$tmp; }; # A
# eval { $var="x $i y"; }; # B
$var="x $i y"; # C
print $var."\n";
}
B and C would print
x 0 y
x 1 y
x 2 y
A print
x $i y
x $i y
x $i y
What’s wrong in A?
eval BLOCKonly catches exceptions, so it’s not relevant to the question. So that leaves us with the following code:The right-hand side of the assignment is the same string in both cases, so why do you expect
$tmpand$varto end up with different values? That makes no sense.So how does one solve your problem? If you want the contents of
$tmpto be used as a Perl code, you need to useeval EXPR, and the content of$tmpactually has to be Perl code.But that’s oh-so-wrong. You’re using
eval EXPRas template system. Use a real tempalte system, like Template-Toolkit. But if you want to keep using templates of the formx $i y, then look into String::Interpolate.