Come for the quick hacks, stay for the epiphanies. | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
When you create a lexical within the condition of an if statement, the scope is notionally the body of the if block, but as shown above in the second example, the scope actually has to extend to any else block also. To achieve this, the life of the lexical has to extend beyond the life of the if block, and so in the first two examples, whilst it's scope is defined by the if/else construct, it's life is bounded by the package level. In effect, it becomes a closure(*incorrect, but common term), within those blocks, but cannot be destroyed until the surrounding scope (the package main in this case) exits. In the third example, there is a scope enclosing the if construct and so the variable can be destroyed when that enclosing scope is exited, rather than waiting for package to finish. I guess setting the refcount to 2 is the mechanism by which closures(*) work? Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham"Think for yourself!" - Abigail In reply to Re: Lexicals in if() scope gotcha!
by BrowserUk
|
|