Hi Christoph!

On Monday 28 Dec 2009 12:04:32 Christoph Friedrich wrote:
> Hello,
> 
> I have searched the internet but didn't found a good answer.
> How do I clone a Perl Object?
> 
> For example like this:
> 
> $a = My::Object->new();
> $b = $a->clone();
> 
> Where $b is an exact copy of $a but in its own memory.
> 

OK, the first answer is that Storable's dclone *probably* does what you want 
as it creates a deep copy of everything and it's implemented in C so it's 
fast.

See:

http://perldoc.perl.org/Storable.html

Storable has been core Perl for a while.

The second and more complex answer is that cloning is not always: 1. Uniquely 
defined. 2. Straightforward that you can rely on dclone. For example: consider 
these examples:

<<<<<<<<<<
my $jack = Person->new({name => "Jack"});

$jack->set_address(Address->new("4 Abby Road"));

my $sophie = Person->new({name => "Sophie"});

$sophie->set_address(Address->new("4 Abby Road"));
>>>>>>>>>

And:

<<<<<<<<<
my $jack = Person->new({name => "Jack"});

my $address = Address->new("4 Abby Road");

$jack->set_address($address);

my $sophie = Person->new({name => "Sophie"});

$sophie->set_address($address);
>>>>>>>>>>

If we clone the "$jack" and "$sophie" persons should we also clone the address 
which it points to? This may do the right thing in the first example, but 
probably not in the second one.

Moreover what if the object contains handles to system services such as files, 
sockets or GUI elements? How should they be cloned.

So my suggestion is that you define a ->clone() method (or a few) based on the 
semantics of what you need and how it should behave, while probably making a 
use of dclone() as a starting point.

Regards and Happy New Year,

        Shlomi Fish

> Greets
> Christoph
> 

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Interview with Ben Collins-Sussman - http://shlom.in/sussman

Bzr is slower than Subversion in combination with Sourceforge. 
( By: http://dazjorz.com/ )

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to