This may be an obvious question, but I'm having trouble wrapping my head around it...I have a reference to a data structure consisting of nested hashes and/or arrays, and I have to pass it (by reference) to a subroutine that does some destructive operations on it.

Before I pass it, however, I'd like to make a copy of the entire data structure, one that will not get modified. None of the following examples do what I need, but they illustrate my train of thought...

# this is an arrayref or hashref containing # other arrayrefs and/or hashrefs $orig_ref; # this makes a copy of the *reference* to the same data # DOESNT WORK $copy_ref = $orig_reg; # this dereferences, then references the original data # DOESNT WORK $copy_ref = ref($orig_ref) eq 'ARRAY' ? \@{$orig_ref} : ref($orig_ref) eq 'HASH' ? \%{$orig_ref} : undef; # this derefs, copies, then refs the copy # SHOULD WORK BUT DOESNT? if(ref($orig_ref) eq 'ARRAY') { @copy = @{$orig_ref}; # deref the original @copy2 = @copy; # COPY the original data? $copy_ref = \@copy2; # ref the copied data? } elsif(ref($orig_ref) eq 'HASH') { %copy = %{$orig_ref}; # deref the original %copy2 = %copy; # COPY the original data? $copy_ref = \%copy2; # ref the copied data? }
I was certain the last example would work...What am I misunderstanding so fundamentally?

In reply to How to copy a referenced data structure? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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, details, 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, summary, 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.