in reply to Re: "eval" and "my" variable weirdness
in thread "eval" and "my" variable weirdness
Absolutely right japhy, but some might find your explanation a bit hard to swallow. It's a complicated topic, so I'll try to illustrate it.
The minimal code illustrating the problem is:
# Module.pm use warnings; package Module; my $thingy = 'thangy'; sub doit { eval 'print "thingy is $thingy\n"'; } 1;
use Module; Module::doit(); # "thingy is "
Each Perl files (both scripts and modules) create a scope. Just like adding {...} around statements creates a scope for the contained statements, use, require, etc create a scope in which the file is executed.
The means the above code is equivalent to:
{ use warnings; package Module; my $thingy = 'thangy'; sub doit { eval 'print "thingy is $thingy\n"'; } 1; } Module::doit(); # "thingy is "
Let's simplify the above to:
{ use warnings; my $thingy = 'thangy'; sub doit { eval 'print "thingy is $thingy\n"'; } } doit(); # "thingy is "
When Perl reached the "}", it doesn't realize you'll still need $thingy (since the eval hasn't run yet), so $thingy is freed. If you added use strict; to the string being evaled, you'd get a strict error. eval's $thingy refers not to the lexical, but to the package variable $main::thingy.
Enter closures. Closures force variables to stick around longer than they normally would:
{ use warnings; my $thingy = 'thangy'; sub doit { print "thingy is $thingy\n"; } } doit(); # "thingy is thangy"
So you need to add a reference to $thingy in your sub so Perl knows (at compile-time) that $thingy is still needed:
{ use warnings; my $thingy = 'thangy'; sub doit { my $ref = \$thingy; # Close over $thingy eval 'print "thingy is $$ref\n"'; } } doit(); # "thingy is thangy"
By "reference", I meant "occurance". In the previous snippet, my reference to $thingy is in the expression creating a reference to $thingy, but it need not be so:
{ use warnings; my $thingy = 'thangy'; sub doit { my $thingy = $thingy; # Close over $thingy eval 'print "thingy is $thingy\n"'; } } doit(); # "thingy is thangy"
Alternatively, use package variables instead of lexical variables. They don't care about scope:
{ use warnings; our $thingy = 'thangy'; sub doit { eval 'print "thingy is $thingy\n"'; } } doit(); # "thingy is thangy"
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: "eval" and "my" variable weirdness
by diotalevi (Canon) on Jun 29, 2006 at 17:17 UTC | |
by ikegami (Patriarch) on Jun 29, 2006 at 17:23 UTC | |
by diotalevi (Canon) on Jun 29, 2006 at 17:24 UTC | |
by ikegami (Patriarch) on Jun 29, 2006 at 17:32 UTC |