Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

How to duplicate objects?

by rapide (Beadle)
on Sep 15, 2008 at 09:39 UTC ( [id://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?

Replies are listed 'Best First'.
Re: How to duplicate objects?
by moritz (Cardinal) on Sep 15, 2008 at 09:40 UTC
    useStorable 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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-03-29 10:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found