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

Re: Copying an Array of Hashes

by tachyon (Chancellor)
on Jul 04, 2001 at 17:30 UTC ( [id://93858]=note: print w/replies, xml ) Need Help??


in reply to Copying an Array of Hashes

Technically there is no such thing as an array of hashes. When we speak of an array of hashes what we really have is an array of references to hashes so the assignment:

@array2 = @array1
will only assign the contents of @array1 (the hash references) to @array2. Here is some code that demonstrates the difference between assignment and completely cloning @array1
print "Here is what happens with assignment\n"; my @array1 = ( {foo=>'foo1', bar=>'bar1' } , {foo=>'foo2', bar=>'bar2' + } ); my @array2 = (); @array2 = @array1; print "\@array1: @array1\n"; print "\@array1: @array2\n"; $array1[0]{foo} = 'new'; print "\$array1[0]{foo}: $array1[0]{foo}\n"; print "\$array2[0]{foo}: $array2[0]{foo}\n"; print "Here is how to clone \@array1\n"; my @array1 = ( {foo=>'foo1', bar=>'bar1' } , {foo=>'foo2', bar=>'bar2' + } ); my @array2 = (); for (@array1) { my %new_hash = %$_; push @array2, \%new_hash; } print "\@array1: @array1\n"; print "\@array1: @array2\n"; $array1[0]{foo} = 'new'; print "\$array1[0]{foo}: $array1[0]{foo}\n"; print "\$array2[0]{foo}: $array2[0]{foo}\n";

Run this code to see the differences. In the first case when we change one of the hash elements both @array1[0]{foo} and @array2[0]{foo} are changed as they both point to the same anonymous hash. In the second case we generate a new anon hash and push references to it into @array2. We now have a true independent clone as you can see by the different references in the array and the different result of changing @array1[0]{foo}.

cheers

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-20 01:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found