Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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?
Replies are listed 'Best First'.
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.

      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.
      Thank you!
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?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (9)
As of 2015-11-25 01:58 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (667 votes), past polls