Why turn warnings off? Turning them on (and autoflushing STDOUT and STDERR, so the output is in order) prints:

Useless use of private variable in void context at myscript.pl line 27 +. factory: 'lulz' eval: 'lulz' factory: 'frunz' Variable "$var" is not available at (eval 2) line 1. Use of uninitialized value $var in concatenation (.) or string at (eva +l 2) line 1. eval: '' factory: 'lulz' eval: 'lulz'

In the first factory, you're using $var in an eval{} block... which is quite different from a string eval(). This isn't an interesting case, and works as you expected anyway.

The difference between your second and third examples is the supposedly useless (as perl tells you) statement $var. The compressed answer is that when you generate the closure in these latter cases, perl has no idea that you're making use of $var in your block, and so it sees no reason to include it in the closure.

After all, all perl sees is a string and some function call (to eval()). But when you explicitly make use of $var in your (third) factory, perl includes it in the closure - not because it knows you're going to need it, but because you included it. When the string eval is then evaluated, it finds $var in the third factory, but can't resolve it in the second factory.

To make sure it is clear what I am referencing from a closure, I always like to explicitly write out which variables I need for it... I'd write something like:

return sub{ my ($code) = ($var); my $estr = "print \"eval: '\$code'\n\""; eval $estr; }


In reply to Re: i don't understand this scope behavior w/ closures and eval by crashtest
in thread i don't understand this scope behavior w/ closures and eval by xandercrews

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.