When I'm doing things like this, I prefer to use a second method aside from new in the parent class to generate the new objects:
sub new {
return bless {}, shift;
}
sub build {
my $self = shift;
my $sub_obj = Other::Class->new;
push @{ $self->{sub_objects} }, $sub_obj;
return $sub_obj;
}
That way, the other objects can be injected into a parent object for tracking purposes (ie. it provides a list of all other in-use objects of the sub types. Here's a very basic example.
my $parent = Obj->new;
my $sub_obj_1 = $parent->build;
my $sub_obj_2 = $parent->build;
for (@{ $parent->{sub_objects} }){
print $_->name . "\n";
}
|