Cloning classes, deep copy revisited (Was: Copy Consturctor in Perl) ..

S

sln

I've got a few packages declared in on file. I need a clone/copy
type functionality for all the ones dealing with a high probability
they will be duplicated (but maybe not) in mass. So I need a clone/copy
type functionality. Some classes need 'deep' cloning, some don't.

I came up with this. See any potential problems using this scenario?
I have given all the classes this same mechanism.

Added comments for usenet reading.
Thanks!


sln
-----------------------------------------------------------------
Example:

package ReS;

sub new
{
my $self;
my $class = shift;
if (defined($_[0]) && ref($_[0]) eq 'ReS') {
$self = {};
my $obj = bless ($self, $class);
return copy($obj, $_[0]);
}
$self = {
...
};
# Should we risk calling set_val that does the
# same thing at the expence of a function call ?
# Sure we could do &set_val.. but still overhead
while (my ($name, $val) = splice (@_, 0, 2)) {
next if (!defined $val);
if (exists $self->{lc $name}) {
$self->{lc $name} = $val;
}
}
return bless ($self, $class);
}
sub clone
{
# clone self, return new
return ReS->new( $_[0]);
}
sub copy
{
# copy other to self, return self
return $_[0] unless (defined $_[1] && ref($_[1]) eq 'ReS');
%{$_[0]} = %{$_[1]};
# do specific deep copying..
# see article on dclone function
$_[0]->{'something'} = ();
@{$_[0]->{'something'}} = @{$_[1]->{'something'}};
return $_[0];
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top