Perl lexicals are like C auto variables, which are generally at the top of the stack.
That is somewhat true and somewhat misleading.
Perl lexicals don't go on the stack. They can't because of the key difference between Perl lexicals and C lexicals: The lifetime of C lexicals matches their scope while Perl lexicals can live forever.
That is, a C lexical is destroyed unconditionally when its scope is exitted. Perl lexicals are initialized (often creating a new instance) when their scope is entered and have one reference to them removed when the scope is exitted. The variable instance will only be destroyed if that was the only remaining reference to it.
So having a sub return a pointer/reference to one of its lexical variables in C/C++ is "a bug" (as it storing a pointer/reference into something that will live past the call into the sub). Having a Perl sub (or 'do' block, etc.) return a reference to one of its lexicals is just fine (as is storing references to any variables anywhere -- though making circular references causes other, less severe, problems).
- tye
In reply to Re^2: Finally, C (lexical life)
by tye
in thread Finally, C
by Ido
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |