in reply to Object scope and DESTROY
Just as stefp pointed out with a concrete example, here's the word as delivered in perltoot.
Destruction happens automatically via Perl's garbage collection (GC) system, which is a quick but somewhat lazy reference-based GC system. To know what to call, Perl insists that the destructor be named DESTROY. Perl's notion of the right time to call a destructor is not well-defined currently, which is why your destructors should not rely on when they are called.
-derby
Update: Geez I have an itchy submit finger today. If we also look at perlguts:
Perl uses an reference count-driven garbage collection mechanism. SVs, AVs,
or HVs (xV for short in the following) start their life with a reference
count of 1. If the reference count of an xV ever drops to 0, then it will
be destroyed and its memory made available for reuse.
This normally doesn't happen at the Perl level unless a variable is
undef'ed or the last variable holding a reference to it is changed or
overwritten.
So what's happening in your code is the first scalar has it's reference count drop to zero. At the end of the block, GC kicks in. In the second case, you pre-maturely force the reference count to zero with undef which cause the scalar to be GC'ed not at the block it's defined in but the first block which completes (and GC kicks in). The third case shows the scalar being GC when it's supposed to be.
|
|---|