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

Discussion in 'Perl Misc' started by sln@netherlands.com, Nov 23, 2008.

  1. Guest

    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];
    }
    , Nov 23, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Neven Klofutar

    Deep cloning

    Neven Klofutar, Jul 7, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    425
    =?Utf-8?B?bG9uZG9uIGNhbGxpbmc=?=
    Jul 7, 2005
  2. Joris Bleys

    deep cloning for container class

    Joris Bleys, Jul 31, 2003, in forum: Java
    Replies:
    1
    Views:
    743
    Joris Bleys
    Jul 31, 2003
  3. nutty
    Replies:
    6
    Views:
    386
    Tom Widmer
    Jun 15, 2006
  4. nagrik
    Replies:
    5
    Views:
    318
  5. Alf P. Steinbach

    Cloning revisited

    Alf P. Steinbach, Aug 31, 2009, in forum: C++
    Replies:
    1
    Views:
    316
    Joshua Maurice
    Aug 31, 2009
Loading...

Share This Page