Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I've created an array of anonymous hashes to act as structures to hold data from some files I'm working on parsing. For various reasons, I need to add an element into the middle of the array that is the same as the one before it except for some minor modifications. I'd been doing this with:
my $new_element = $hash_array[$index];
Of course, I've noticed that this just makes $new_element a reference to the same anonymous hash. What is the best way to make $new_element be a reference to an anonymous hash with the same data as the anonymous hash in $hash_array$index, so that I may splice it in?

(Side question: When using splice and replacing a run of 0 length, are new elements put at the offset position, or after?)

Thanks in advance, wise Monks.

Replies are listed 'Best First'.
Re: Copy of an anonymous hash?
by holli (Abbot) on Apr 26, 2005 at 07:33 UTC
    my $new_element = {%{$hash_array[$index]}};

    holli, /regexed monk/
      That works, but only if the hash contains simple scalars. If it contains any references, the reference will be copied, so you'll have two references to the same thingy. If that matters, I recommend using the Storable module and its dclone function.

      This won't solve the problem of references to items outside the structure, but that's not usually a problem that needs solving anyway.

      I believe
      my $new_element = \%{$hash_array[$index]};
      would also work. (Right?)

      UPDATE: I meant, my referencing syntax would work as well as hollis. This is right... right?

        Nope, it'll still point to the same underlying hash.

        freebie:~ 702> perl -le '$a={qw(a b)};$b=\%{$a};print "$a\t$b"' HASH(0x804c844) HASH(0x804c844)
Re: Copy of an anonymous hash?
by pelagic (Priest) on Apr 26, 2005 at 11:42 UTC
      deep copy is not always the solution:

      There is shallow copy in one extreme and deep copy in the other an in the middle lots of intermediate solutions, which one is the good one depends on the particular data representation.

      For instance, if you are cloning an object representing an XML node, you will like to deep-copy all its children but not the pointer to its parent.

        100% agreed!
        I didn't say deep copy is the solution, I said it's the topic ;)


        Shallow copy is usually a good solution: all you need is to do a shallow copy whenever you change a structure.