Gary Stainburn wrote: > Hi folks, > > My first forrey into Perl objects sees me trying to model a railway. I've got > a hash of named blocks of track, which is added to when I create a new block > object. > > My problem is one of destroying a block (object), making sure that I have no > memory leakage. > > I create a new track block such: > > my $T1=Trainset->track('T1','Block'); > > This also created $Trainset::_BLOCKS{T1} which references the object.
Hi Gary, I really think your problem comes in here. I would always be leery of situations where you have to use the namespace prefix explicitly. It generally casts too broad a net for most purposes. I think you are doing the right thing--sort of--with Trainset. This is assumig that you have a Trainset class as well as a Track class. I would suggest, though, that you assign new $track to your object through $train_set, your Trainset object, rather than through the class itself. This apporoach would give you the flexibility to have mutliple Trainset objects, thus make your class more robust. > > > My problem is how can I destroy the object when I no longer want it? > > If I call > > $T1=$T1->delete; > > Then the object is destroyed (display in DESTROY shows this). However, if I > simply call > > $T1->delete; > > The object isn't destroyed because even though the ref in %_BLOCKS is deleted, > the ref in $T1 is still there. Is there and way to ensure that the object is > destroyed - i.e. force the refcount to zero? > > The only solution I've come up with is to explicitly call DESTROY from within > the delete function, and within DESTROY empty the hash. Is this sufficient, > or will this still tie up memory? Is there a better way? > > -- > Gary Stainburn Overall, I would suggest that you steer clear of internal references in your objects when possible. It is much better to make a container class, then delete contained objects from the container. Generally you would want to avoid having other references to the contained objects, except through the methods of the container [Trainset] object. package Trainset; use strict, warnings et. al.; use Exporter; our @ISA = qw/Eporter/; sub new { my $class = shift; my $self = {}; bless $self, $class; $self->initialize(@_); } sub initialize { my $self = shift; $self->{'set ID'} = shift; #... assign other set-level scalar info hard-coded into # the parameter list ...then: push @{$self->{'tracks'}}, (@_}; # to allow initialization with an existing list } sub add_track { my $self = shift; my $track = shift; push @{$self->{'tracks'}}, $track; } ... Let your train set be one object, and your tracks be represented by another class. Keep each as simple and straightforward as possible. Joseph -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>