Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Re: how do I copy an array of objects?

by thinker (Parson)
on Nov 12, 2001 at 21:02 UTC ( [id://124859]=note: print w/replies, xml ) Need Help??


in reply to Re: how do I copy an array of objects?
in thread how do I copy an array of objects?

>># NOTE:
>># $OBJS is an array of objects, and array elements can also be arrays of objects

I should have read the question better before I answered :-)
The code I gave will only dereference down 1 layer.
The code below will explain this better, I hope.
Anyway, I think what you really want is Clone.
I just downloaded it to test this code, and already I see it as an invaluable tool in my Perl toolbox.
Here is an example of how my earlier code fails, and how Clone can help you.

Good luck

thinker

#!/usr/bin/perl -w use strict; use Clone qw(clone); my $original =[1,2,[3,4,5]]; my $shallow_original=$original; my $deep_original=[@$original]; #deep, but not deep enough!! my $clone_original=clone($original); # this behaves fine. $original->[1]=42; $original->[2][1]=77; print "original: @$original\n"; print "shallow: @$shallow_original\n"; print "deep: @$deep_original\n"; print "shallow[2][1]: $shallow_original->[2][1]\n"; print "deep[2][1]: $deep_original->[2][1]\n"; print "clone[2][1]: $clone_original->[2][1]\n";
The output of which is
original: 1 42 ARRAY(0x80cf9a4) shallow: 1 42 ARRAY(0x80cf9a4) deep: 1 2 ARRAY(0x80cf9a4) shallow[2][1]: 77 deep[2][1]: 77 clone[2][1]: 4

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://124859]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-25 18:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found