Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

How to duplicate objects?

by rapide (Beadle)
on Sep 15, 2008 at 09:39 UTC ( #711416=perlquestion: print w/ replies, xml ) Need Help??
rapide has asked for the wisdom of the Perl Monks concerning the following question:

(I've googled and ran a search here but unable to find the answer)

Is there an easy way to duplicate objects without looping through each key and value?
Basically, if I have object A Is there possible to say B = A without copying the reference?

Comment on How to duplicate objects?
Re: How to duplicate objects?
by moritz (Cardinal) on Sep 15, 2008 at 09:40 UTC
    use Storable qw(dclone);
    my $clone = dclone($object);

    Storable is a core module, on CPAN you can also find Clone.

      Thank you!

      Clone et al will normally work, but there are some cases where they won't work. Even worse, there are cases where they will partially work in which case you'll get bitten a long way down the line by obscure "can't happen" bugs.

      In the general case, you need to use the object's clone() method, and if it doesn't have one - patches welcome!

        Especially, decide what you want to do with GLOB objects. IIRC, Storable will refuse to clone them, but Clone will do it.
Re: How to duplicate objects?
by Joost (Canon) on Sep 15, 2008 at 10:24 UTC
    You can do something like this, also, assuming the object is implemented as a hash reference:
    my $copy = bless { %$original }, ref $original;
    Note that this does not clone any object referenced in the $original (those references will just get copied), so this does the minimal amount of work - while the Storable solution above copies everything it can find.

    Quite often, what's actually needed is something in between these two extremes, which means you'll probably end up with the objects providing their own clone() and/or freeze() method(s).

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://711416]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (13)
As of 2014-09-01 09:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (300 votes), past polls