in reply to Variable scoping outside subs

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