in reply to Using an "outer" lexical in a sub?
Compare this:
With this:package foo; our $n = 1; package main; print "n = ", $foo::n , $/; # n = 1
package foo; my $n = 1; package main; print "n = ", $foo::n , $/; # nothing
A related topic is the behaviour of closures, which was mentioned by several other monks above. One of the less obvious behaviours of closures can be seen in the following example:
The inner sub 'bar' keeps a reference to the instance of '$n' that existed during the first call to 'foo'. People frequently run into this problem when they first start using mod_perl with Apache::Registry, as documented here:sub foo { my $n = 1; print $n; bar(); print $n; bar(); sub bar { $n++; } } foo(); foo(); #output 1211
|
|---|