http://www.perlmonks.org?node_id=334185


in reply to Re: Global objects and GC
in thread Global objects and GC

I had similar troubles with global destruction. I found this thread (Object reference disappearing during global destruction) and I thought I understood what was my error: to rely on the reference-count mechanism even during global destruction. Seeing the topic popping out again, I decided to do some experimentations in order to acquire a (?better) grasp on the subject. Here's the code:
use strict; use warnings; package Bar; use Devel::Peek 'Dump'; sub new { bless [], shift } sub bar { print "Hi, I'm a bar instance\n\n" } sub dump { print "This is my ID card:\n"; Dump( shift ) } package Foo; sub new { my $bar = Bar->new(); bless { bar => $bar }, shift; } sub DESTROY { my $self = shift; $self->{ bar }->bar(); $self->{ bar }->dump(); } package main; my $f = Foo->new();
My expectation was to see a message like Can't call method "bar" on an undefined value with unpredictable frequence. I run the script several times, without warnings. Since this is a semidecidible issue, and I don't have all that time :), I ask if my understanding is correct, and further explanations if appropriate. Thank you.

Replies are listed 'Best First'.
Re: Re: Re: Global objects and GC
by chromatic (Archbishop) on Mar 05, 2004 at 20:54 UTC

    At the end of the program, I'd expect $f to go out of scope first, calling its DESTROY. Since it contains a reference to a Bar, the contained object should still exist, so things are okay.

    If $f were global or if it had more than one reference, things might be stickier.