-
Notifications
You must be signed in to change notification settings - Fork 19
Destructors
(Hat tip to Damian for prompting me on this. I had been meaning to get around to it, but he was kind enough to provide me with the background. Heck, I could have just cut-n-pasted his email)
Just as we have constructors, we also need destructors. These are special methods called during object destruction to ensure that everything that needs to be cleaned up/finalized, is cleaned up/finalized.
Core Perl has an issue here:
#!/usr/bin/env perl
use Less::Boilerplate; # personal version of Modern::Perl
package Parent {
sub new { bless {} => shift }
sub inherited { say "Inherited" }
sub DESTROY { say "Parent" }
}
package Child {
our @ISA = 'Parent';
sub new { bless {} => shift }
sub DESTROY { say "Child" }
}
{
my $thing = Child->new;
$thing->inherited;
}
say "Done";
Running that prints:
Inherited
Child
Done
Note that Parent
is not printed because the parent destructor is not called. Thus, you need to call $self->next::method
at the end of every DESTROY
.
Moose has sane object destruction via DEMOLISH, but Cor ain't Moose. Moose has BUILD
and DEMOLISH
for construction/destruction, so Cor should have CONSTRUCT
and DESTRUCT
for its object construction/destruction.
Most of the time you won't need a DESTRUCT
method.
method DESTRUCT ($is_global_destruction) {
if ($is_global_destruction) {
...
}
else {
...
}
}
Corinna—Bringing Modern OO to Perl