Update: Wow, it took me a long time to test and compose this (there weren't any replies when I started). The other replies indicate a closure problem, so I may be barking up the wrong tree here.
Update 2: Yup. Wrong tree. Wrong yard, even. For some reason (I'll blame fatigue) I completely missed the fact that the ellipses in the eval meant "some code deleted here" (even though I understood that perfectly well in the rest of the OP) rather than literal dot-dot-dot's as part of the print statement. Duh. :-)
From eval for eval EXPR:
the return value of EXPR is parsed and executed as if it were a little Perl programand later, as part of an example, we are told that eval "$x"; "run[s] the code contained in the variable $x".
I'm going to jump to the end in an attempt to explain what I think might be going on. Your example has $var = 'this string', but since eval is running code it might be easier to follow what's going on if we changed that to something else, say $var = 'print "hi\n"'. I also added a call to mysub() and simplified that routine.
This prints:my $var; mysub(); sub initialize { $var = 'print "hi\n"'; print "in initialize: $var\n"; } sub mysub { print "in mysub: $var\n"; } BEGIN { initialize() }
This example shows that $var is set to the expected value in mysub, so the problem must be with the eval.in initialize: print "hi\n" in mysub: print "hi\n"
Now change mysub as follows (a simplification of your original eval):
The output is:sub mysub { print "in mysub: $var\n"; print eval("$var"), "\n"; }
Adding eval("$var") added two lines of output, hi and 1. The first line ("hi") is from evaluating the code in $var (print "hi\n"), and the second is from printing the return value ("1") from the eval.in initialize: print "hi\n" in mysub: print "hi\n" hi 1
Now change mysub to your original code and print $@ in case there are any errors in the eval:
Output:sub mysub { print "in mysub: $var\n"; print eval("...$var..."), "\n"; print $@ if $@; }
$var is interpolated and the code in the eval is executed, but that code (...print "hi\n"...) contains a syntax error (it's a bit more obvious now, isn't it?).in initialize: print "hi\n" in mysub: print "hi\n" syntax error at (eval 1) line 1, near "..."
Finally, change mysub to:
(you can also remove the quotes around $var in the eval). Output:sub mysub { print "in mysub: $var\n"; print eval("$var"), "\n"; }
which behaves as we would expect.in initialize: print "hi\n" in mysub: print "hi\n" hi 1
In summary, the problem had nothing to do with initializing the variable, it was due to the fact that the ellipses in your print statement created syntactically invalid code. Moral of the story: check $@ after an eval. :-)
In reply to Re: quantum behavior in perl?
by bobf
in thread quantum behavior in perl?
by b4swine
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |