You need to include more details or we can only guess at what is meant.

Here is an example of a guess.

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 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.

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:

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")->();
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...)

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).


In reply to Re: Eval doesn't see lexicals by tilly
in thread Eval doesn't see lexicals by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.