in reply to Rules of Lexical Scoping
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).
I think that's quite inaccurate.While that may be what seems to happen and it may be what should happen, that's not what really happens. Lexical variables are cleared on block exit and re-used unless there are still references to them.
That means
Lexical variables aren't discarded and recreated. They are simply cleared.
The clearing of a lexical variable occurs when the block is exited, not when it is entered. And only if the my was executed since the block was entered.
A new variable is created if needed when the block is exited, not when it is entered. And only if the my was executed since the block was entered.
In more details,
Perl_save_clearsv (scope.c in perl.git) is called when my is executed [via SAVECLEARSV (scope.h in perl.git) and pp_padsv (pp_hot.c in perl.git)]. It places a directive on the stack (SAVEt_CLEARSV) to clear the variable on scope exit.
On scope exit, Perl_leave_scope (scope.c in perl.git) is called to unwind the stack. When the SAVEt_CLEARSV directive placed by the run-time execution of my is encountered, the variable is either cleared (if SvREFCNT(sv) <= 1 && !SvOBJECT(sv)) or replaced.
These details are somewhat visible in the following example:
sub test { my ($reset) = @_; my $x if $reset; print ++$x, "\n"; } test(0); # 1 test(0); # 2 test(1); # 3 test(0); # 1 test(0); # 2
Perl 5.8.8
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Rules of Lexical Scoping
by ysth (Canon) on Nov 11, 2007 at 06:33 UTC | |
|
Re^2: Rules of Lexical Scoping
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 |