in reply to Eval doesn't see lexicals
Here is an example of a guess.
The problem is that when will_not_be_a_closure exits, Perl sees no references to %serial_of and so cleans it up. This is known behaviour and the last I heard it is unlikely to change.sub will_not_be_a_closure { my %serial_of = @_; return sub { eval 'use Data::Dumper; print Dumper \%serial_of;'; } } will_not_be_a_closure(foo=>"bar")->();
The solution is to use that variable in any trivial way in the subroutine so that you still have a reference to it. If you use all of the variables that you might use in trivial ways, they will all be there and the eval will find the ones that you want. Like this:
Note that in general if you need to use closures and eval, it is better to try to use eval to generate closures rather than to call eval from within a closure. (I know, there are plenty of cases where you can't feasibly do this. But if you can...)sub will_be_a_closure { my %serial_of = @_; return sub { my $x = $serial_of{x}; eval 'use Data::Dumper; print Dumper \%serial_of;'; } } will_be_a_closure(foo=>"bar")->();
Two random tips on eval. First, it is good when you use eval to be in the habit of always checking $@ afterwards. Even for trivial evals. Secondly go to the very bottom of perlsyn and read about Plain Old Comments (Not!) and use that change the usual (eval 666) in error messages into something useful (or at least greppable in your source to find the source of the failing eval).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Eval doesn't see lexicals
by Anonymous Monk on Nov 02, 2005 at 02:43 UTC | |
by tilly (Archbishop) on Nov 02, 2005 at 02:53 UTC | |
by dave_the_m (Monsignor) on Nov 02, 2005 at 10:39 UTC |