Weak links in Perl
How do I create weak references to objects in perl, so when the object goes out of scope, the reference count is freed?
I tried using DESTROY subtitle to break circular links.
sub DESTROY{
my $p = shift;
delete $p->{__tree__};
delete $p->{tokenizers};
delete $p->{toke};
}
Please, help.
source to share
You cannot "call" destroy - the problem here is that perl is reference-counting - every reference to a thing is counted, and only when the reference count drops to zero that it can be deallocated / destroyed / garbage collected.
DESTROY
is a special method that is called inside the object to perform cleaning tasks when this happens. It doesn't delete the object, it just lets you do some final tricks when it dies.
Take a look at the module Scalar::Util
. It includes a method weaken
that does exactly what you asked for.
lvalue $ ref will be translated into a weak reference. This means that it will not contain a reference count for the object it refers to. Also, when the reference count of this object reaches zero, the reference will be set to undef. This function mutates the lvalue passed as its argument and returns no value.
This is useful for keeping copies of references, but you don't want the DESTROY-ed to run at its normal time.
source to share
From perldoc :
You can break circular links by creating a "weak link". A weak reference does not increment the reference count for a variable, which means that the object can go out of scope and be destroyed. You can relax the link with the relaxed function exported by the Scalar :: Util module .
Here we can make the first example more secure:
use Scalar::Util 'weaken';
my $foo = {};
my $bar = { foo => $foo };
$foo->{bar} = $bar;
weaken $foo->{bar};
Values ββfrom
$foo
to$bar
have been relaxed. When a variable$bar
goes out of scope, it will be garbage collected. The next time you look at the value$foo->{bar} key
, it will beundef
.This action at a distance can be confusing, so you must be careful about using the Debuff. You have to loosen the reference in the variable that will go out of scope first. Thus, the longer variable will hold the expected reference until it goes out of scope.
source to share