I believe one part of your code is actually closer to eval('...$var...') (note the single quotes). And, yes, this is likely a FAQ somewhere.

A reference to a Perl sub "closes over" any lexical variables that are in scope when the reference to the sub is taken. One reference to a simple, named sub is taken and stored in the package's symbol table ("stash") when the sub is compiled. This is how a simple, named sub can access lexical variables declared in their surrounding scope.

For the sake of efficiency, these references only "close over" lexical variables that the subroutine makes use of. Since your mysub() does not make any (direct) use of $var, $var isn't closed over. So when you call mysub(), the reconstruction of the scope to include any closed-over lexicals does not provide access to $var.

If your code really did say eval("...$var..."), then that would get compiled into the equivalent of eval("...".$var."...") so $var would have been directly used by mysub() and so would have been closed over.

Yes, this quirk is considered unfortunate and so there is a desire to "fix" it. But I'm aware of a plan for how it could be reasonably fixed, so I wouldn't hold my breath. You'll need to work around it by mentioning $var directly in mysub(), though you don't have to print it.

- tye        


In reply to Re: quantum behavior in perl? (cheap closures) by tye
in thread quantum behavior in perl? by b4swine

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.