my $foo={a => 1, b => 2}; # Some sort of reference scalar.
my $foo_=new Devel::WeakRef $foo;
my $bar=$foo_->deref; # Hard ref through dereference
$foo_->deref->{c}=3; # Dereference
$foo=$bar=77; # OK, hash collected
$foo_->deref; # Yields undef now
$foo_->empty; # True now.
Currently this also works:
$$foo_->{a};
But this dies with a stern message:
$$foo_=$new_thingy; # Nope! Weak ref must never change referents.
This hash table has weak references as values:
tie my %table, Devel::WeakRef::Table;
$table{key1}=$some_object;
$table{key2}=$some_other_object;
$table{key1}=$yet_another_object; # OK to replace keys like this
bless) that does not contribute to the object's reference count; thus, the
object's storage will be freed (and its destructor invoked) when only weak
references remain to it. (It is fine to have multiple weak references to a
single object.) The
deref method derefences the weak reference. Dereferencing a weak reference whose
target has already been destroyed results in undef.
empty tests if the reference is invalid; $ref->empty is equivalent to
!defined $ref->deref. For now, you can just use Perl's normal scalar dereference to the same effect; but
be sure to use this for reading only. This interface may change.
The package Devel::WeakRef::Table may be used to tie hashes so as to make their values all weak references. This is useful for caches in particular, where it would be more annoying to have to explicitly dereference the value each time.
The most likely applications of this module are:
The module attempts to catch attempts to directly set the target of a weak
reference in a scalar dereference operation as an lvalue, and dies
abruptly. It tries to do so as nicely as possible, but it is not feasible
to 100% protect the environment in this case. In other words, if you plan
on having this error occur, do not plan on
eval-BLOCKing it and expecting everything to be dandy later.
Tied weak tables have not been tested as well as the bare references. There may be unforeseen memory leaks (presumably, not in the referred-to objects themselves, but in supporting data areas--this would affect raw memory usage, not collection of the reference targets).
Putting a weak ref on a reference object places extension-magic (~, see
perlguts(1P)) on that object. This could conflict with other user extensions using
custom magic. To avoid this, Devel::WeakRef specifically looks for its own magic and only its own magic; however,
another extension might not do so for itself and become extremely confused,
if it was specifically looking for its own magic (probably not so common).