Neat failure, thanks for posting. Here's a try at an explain. That $var is compiled prior to test(), thus test() can refer to it (you can't move $var after test()), acting as a closure, as has been noted (++). However, as other posters have noted, line 6 does not get executed, so the assignment is never performed. The value of $var is undefined when printed, as a result.

Now, I actually rather believe that storage is allocated on-the-fly, during the call to test(), rather than at compilation-time.

Also, here's some additional test code I wroteup just to check some of my thoughts.

use strict; &f; #"pre=> ", "post=>2" my $v = 1; &f; #pre=>1", "post=>3" exit; sub f { print "pre=>$v\n"; $v += 2; print "post=>$v\n"; }
update

Here's some further code that was illustrative to me.

#this code proves that scratchpads keep lexicals around, #not mere copies of those lexicals; something like reference #counting of lexicals is occuring with closures - the details #don't really matter - the $v lexical persists in both the f1 #and f2 closures, not a mere "copy" of $v. sub f_maker { my $v = 1; my $f1 = sub { print "f1_pre =>$v\n"; $v++; print "f1_post=>$v\n"; }; my $f2 = sub { print "f2_pre =>$v\n"; $v++; print "f2_post=>$v\n"; }; return ($f1, $f2); } my ($f1, $f2) = &f_maker; &$f1; &$f2; &$f1; __OUTPUT__ f1_pre =>1 f1_post=>2 f2_pre =>2 f2_post=>3 f1_pre =>3 f1_post=>4

In reply to Re: Variable scoping outside subs by welchavw
in thread Variable scoping outside subs by xiper

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.