Let's say I have a Perl class that has a DESTROY method. This method is used to implicitly release an external resource, such as a file handle or database transaction.
Given an instance of this class, I would like to explicitly destroy it. The primary purpose of this is to cause the DESTROY method to be called so the external resource can be released. However, having the "object" itself released from memory would be an added benefit.
How can I do this? I have considered directly calling the DESTROY method and undefining any variables that reference the object.
Perl5 objects get destructed as soon as the last reference to them disappears, unless you have self-referential structures (see Destructors and the Two phase garbage collection paragraph after that for some interesting information).
If you don't have self-references, you don't need to worry about anything, the DESTROY
method will be called when it needs to be; trying to destruct the object yourself would not be safe (how can you be sure the object isn't references somewhere else), unless you're also doing reference counting yourself (if that's actually possible, and that would be duplicating perl's efforts, which isn't such a good idea).
So I'd say, as long as you don't have cyclic references:
release
/close
/dispose
/whatever method (that your DESTROY
code could call too).If you do have cyclic references, you'll need to be much more careful, and use weak references (see Scalar::Util
) to break the cycles.
(In other words, I don't know of a way to explicitly delete
a perl object. That doesn't work well with a reference-counted garbage collection system.)
You can use undef to explicitly destroy an object. The below code illustrates it.
package MyPackage;
sub new {
print "In new\n";
return bless {};
}
sub DESTROY {
print "In DESTROY\n";
}
package main;
my $Obj = MyPackage->new();
<STDIN>;
undef $Obj;
<STDIN>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With