At all times Perl follows the following five basic rules:
1. Any *use* of a lexical variable is, at *compile* time, matched against the nearest *lexically* (not dynmically) matching 'my' declaration.
2. Each time a block with a 'my' declaration is entered, a new instance of that lexical is created, and each time the block is exited, that instance is discarded (of course, if something else holds a reference to it, then the actual thinbg itself continues to exist, it is just not accessible via the lexical name). The one proviso to this is that the first instance exists from the moment of creation of the sub or file it resides in, rather from entry into the block during first execution.
3. At the creation time of a sub that references an outer lexical, that sub captures the current instance of that lexical. If there is no currently valid instance, a warning is issued, and a new undef value is 'captured' instead. For named subs, creation time equals compilation time; for anonymous subs, creation time is later, when you execute the 'sub' bit.
4. For our purposes, a string eval is just a sub that is compiled once, executed once, then discarded.
5. When a sub has captured an instance, any mention of '$x' which is lexically contained within that sub, such as in an eval or nested anonymous sub, will see that captured instance rather than the outer one.
Okay, I've skipped a few subtleties, such as what constitutes a sub, and what happens after you undef a sub, but that's the jist of it.
In reply to Rules of Lexical Scoping by ysth
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |