Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Does anyone know of a way to safely serialize (i.e. freeze/thaw) a data structure that has weak references? Here's an example:
use strict; use Storable qw(freeze thaw); use Scalar::Util qw(weaken isweak); # make a circular reference, then weaken it my $a={}; $a->{a}=\$a; weaken($a->{a}); # looks like we're ok isweak($a->{a}) || die; # serilize it my $b=freeze($a); # and unpack it my $c=thaw($b); # check if the weak reference survived the freeze isweak($c->{a}) || die "nope!";
And it dies with "nope!". So far I've found one package on CPAN, "OOPS", that has planned support for serialzing weak references, but nothing currently exists... or maybe something does?

Replies are listed 'Best First'.
Re: serializable weak references
by perrin (Chancellor) on May 19, 2004 at 17:00 UTC
    If you are working with objects, you can use the hooks that Storable provides to provide special behavior that will preserve the weak refs. (I would probably make notes in a special "__weak_refs" key in the hash and then use that to know which ones to weaken during the thaw phase.) This is probably the closest you can get without hacking the source. You could try hacking Data::Dumper too.
Re: serializable weak references
by halley (Prior) on May 20, 2004 at 13:51 UTC
    I would expect a weak reference should be serialized as undef? And if you needed to reconnect later, such as during thaw, then you must also keep a symbolic sort of reference, such as the database row id for the referred ojbect.

    --
    [ e d @ h a l l e y . c c ]