Here are a couple of rudimentary classes for creating a File object which contains a reference to a Dir object which in turn contains the File object:
I threw in a weaken on the File's dir attribute but I'm not really sure if that's needed. My understanding is that weaken does not increment the reference count. So if I delete the Dir object, the files will still reference the Dir and it will therefore remain in existence for as long as any File object references the Dir. But with the weaken keyword, if I delete the Dir, the Files can no longer reference the Dir. But is this really a big deal? I don't really see the harm in leaving it as a strong reference. But maybe I'm wrong and this is considered to be a memory leak. Can someone shed some light on this for me?package Practice::File; use v5.38; use Cwd; use Scalar::Util qw(weaken); sub new { my $class = shift; my $self = {}; $self->{name} = shift; bless $self, $class; return $self; } sub dir { my $self = shift; return $self->{dir}->{dir}; } sub add_dir { my $self = shift; my $dir = shift; $self->{dir} = $dir; weaken($self->{dir}); # <=============== Is not using weaken h +ere a really bad idea? $self->{dir}->add_file($self); } sub path { my $self = shift; my $path = $self->{name}; if (defined $self->{dir}) { $path = $self->{dir}->path . '/' . $path; } return $path; } 1; package Practice::Dir; use v5.38; use Cwd; sub new { my $class = shift; my $self = {}; $self->{dir} = cwd(); $self->{files} = []; bless $self, $class; return $self; } sub add_file { my $self = shift; my $file = shift; push @{$self->{files}}, $file; } 1;
$PM = "Perl Monk's";
$MC = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest Vicar Parson";
$nysus = $PM . ' ' . $MC;
Click here if you love Perl Monks
In reply to Should I use weaken on an object attribute containing a reference to an object which contains reference back to original object? by nysus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |