[pm-h] When to use "weaken"?

Michael R. Davis mrdvt92 at yahoo.com
Thu Jan 23 20:51:49 PST 2014


>> I would do the weaken in the the child. You are passing the parent
>> reference to the child. The child knows that it doesn't need to own the
>> parent reference, so the child should weaken the reference.
>
> I will try weakening in the children.  

It's nice that all my children inherit from one Base object.

I think this is all I need to do.

$ svn diff
Index: lib/XXX/Base.pm
===================================================================
--- lib/XXX/Base.pm    (revision 3433)
+++ lib/XXX/Base.pm    (working copy)
@@ -1,4 +1,5 @@
 package XXX::Base;
+use Scalar::Util qw{weaken};
 use base qw{Package::New};
 use strict;
 use warnings;
@@ -23,6 +24,25 @@
 =head1 USAGE
+
+=head2 initialize
+
+Provides automatic weakening of the parent property.
+
+=cut
+
+sub initialize {
+  my $self=shift;
+  %$self=@_;
+  weaken($self->{"parent"})
+    if (exists($self->{"parent"}) and ref($self->{"parent"}));
+  return;
+}
+
+
 =head1 METHODS
 =head2 parent
@@ -31,7 +51,10 @@
 sub parent {
   my $self=shift;
-  $self->{"parent"}=shift if @_;
+  if (@_) {
+    $self->{"parent"}=shift;
+    weaken($self->{"parent"});
+  }
   return defined($self->{"parent"}) ? $self->{"parent"} : $self;
 }


More information about the Houston mailing list