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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Rules of Lexical Scoping
by ikegami (Patriarch) on Nov 11, 2007 at 05:59 UTC | |
by ysth (Canon) on Nov 11, 2007 at 06:33 UTC | |
by jdporter (Paladin) on Nov 11, 2007 at 13:43 UTC | |
by ysth (Canon) on Nov 11, 2007 at 22:51 UTC | |
by jdporter (Paladin) on Nov 12, 2007 at 02:10 UTC | |
by tye (Sage) on Nov 12, 2007 at 02:39 UTC | |
by ikegami (Patriarch) on Nov 12, 2007 at 04:47 UTC | |
by tye (Sage) on Nov 12, 2007 at 05:40 UTC | |
by ysth (Canon) on Nov 12, 2007 at 07:37 UTC |