Perhaps you want something like what I've posted below? It keeps a copy of the options passed to the parent constructor and passes them, along with any new options, to the child constructor. I'm not sure if it's something like this you are looking for, or if I am way off base.
update: Added an iterator to the main script to show results of child creation. In a real-world example, you'd probably want methods to access the children, rather than digging around in the package internals as I have done below.
package Parent;
use strict;
use Child;
sub new {
my ($class, %opts) = @_;
my $self = bless( {
_opts => \%opts, # save parent options
_children => [] # an array of children
}, $class);
return $self;
}
sub new_child {
my ($self, %opts) = @_;
my $child = Child->new(
%{ $self->{_opts} }, # the saved parent options
%opts # the new child options
);
# save this child inside the parent object
push @{ $self->{_children} }, $child;
return $child;
}
1;
package Child;
use strict;
sub new {
my ($class, %opts) = @_;
my $self = bless( { _opts => \%opts }, $class );
return $self;
}
1;
package main;
use strict;
use Parent;
# Create the parent object. We will create child objects
# with it and save those child objects within the parent.
my $p = Parent->new( foo => 1, bar => 2 );
# Create the first child. Pass an extra option in.
my $c1 = $p->new_child( baz => 3 );
# Create a second child. Give it different options.
my $c2 = $p->new_child( qux => 4, yeah => 5 );
# Iterate through children and see which options they got.
for my $child ( @{ $p->{_children} } ) {
while ( my ($k, $v) = each %{ $child->{_opts} } ) {
print "$k ==> $v\n";
}
print "\n";
}