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
In reply to Re: Rules of Lexical Scoping
by ikegami
in thread Rules of Lexical Scoping
by ysth
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |