Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Copying an Array of Hashes

by dooberwah (Pilgrim)
on Jul 04, 2001 at 01:26 UTC ( #93693=categorized question: print w/replies, xml ) Need Help??
Contributed by dooberwah on Jul 04, 2001 at 01:26 UTC
Q&A  > arrays


Is there any easy way for copying an array of hashes? My understanding is that @array2 = @array1 (where @array1 is an array of hashes) won't make a new copy because it just copies the refrences into @array2. I'd like to know if there's an easier way of making a copy of @array1 than looping through it and copying each element.

Answer: Copying an Array of Hashes
contributed by tachyon

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}.


Answer: Copying an Array of Hashes
contributed by Masem

The best way to copy any complex data structure is to use something like the Clone module; it will make a complete copy of all nested data items for you. Mind you, if you are trying to make a new array but with the same references to hashes, you'll have to do a element-by-element copy, as Clone will try to make copies of the hashes instead.

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    marioroy At a large firm, had to awaken a security guy a few times so that nobody would catch him sleeping.
    marioroy On a large dairy farm, almost went off the road with a 10 wheeler from exhaustion. On the farm, almost went off the silo with a big tractor. At the Fransiscan monastery, almost slipped off the dome while painting it.
    [marioroy]: In Saudi Arabia caught fire but didn't burn. I think angels exist.
    Lady_Aleena clean up after dinner finally.
    [Discipulus]: uch! so we are twice lucky to have MCE..;=)
    [marioroy]: Working a midnight graveyard shift, on the way home ran out of gas. just 2 minutes later somebody stops with a small tank of gas. It's wierd. There's always someone nearby for some reason.
    [Lady_Aleena]: I was the one who stop[ed in the middle of a cold night to pick up a small family walking to a gas station. I got a few gallons of free gas for the round trip, and the grandmother said she'd pray for me.
    [marioroy]: Folks do not know it, but MCE was ridiculously difficult. At Niagra Falls, heard a voice on enabling Grace while in the mist boat. That 10x performance is possible.
    [marioroy]: Lady_Aleena Angels on earth are real people. That's awesome.

    How do I use this? | Other CB clients
    Other Users?
    Others meditating upon the Monastery: (9)
    As of 2017-05-29 08:24 GMT
    Find Nodes?
      Voting Booth?