in reply to when is destroy function called
Maybe this is helpful?
use v5.14; package Mouth { use Moo; has teeth => (is => 'ro'); sub DESTROY { say 'Mouth->DESTROY' } } package Head { use Moo; has mouth => (is => 'ro'); sub DESTROY { say 'Head->DESTROY' } } my $mouth = Mouth->new(teeth => []); my $head = Head->new(mouth => $mouth); say 'undefining $mouth'; # Note: DESTROY not called, because $head still refers to $mouth undef $mouth; say 'undefining $head'; # Now both DESTROY methods will be called undef $head;
Compare that with the ZombieHead which allows its mouth to randomly disintegrate by using a weak reference...
use v5.14; package Mouth { use Moo; has teeth => (is => 'ro'); sub DESTROY { say 'Mouth->DESTROY' } } package ZombieHead { use Moo; has mouth => (is => 'ro', weak_ref => 1); sub DESTROY { say 'Head->DESTROY' } } my $mouth = Mouth->new(teeth => []); my $head = ZombieHead->new(mouth => $mouth); say 'undefining $mouth'; undef $mouth; # DESTROY is called!! say 'undefining $head'; undef $head;
References can be weakened using Scalar::Util.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: when is destroy function called
by 7stud (Deacon) on Feb 27, 2013 at 18:26 UTC |