Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Comment on

( #3333=superdoc: print w/ replies, xml ) Need Help??
Dear Monks, having coded a lot in C++ in the last few months I'm now a bit paranoid and probably to C++-ish in my thinking. Therefore I'd be more than happy to be enlightened on the following problem by a real Perl guru :-)

I've created a class (let's call it CLASS) that has a nested data structure like this:

my $self = { nest => [ [ [ 1, 2, 3 ], [ 4, 5, 6 ], ], ], more => [ 3, 2, 1 ] };
Then I want to copy it like this:
my $c1 = new CLASS; my $c2 = $c1;
And next to that I need to change a value in the arrays of $c2. Since I have the instance variables as lots of references changing a value in $c2 always changes the corresponding value in $c1.

I had hoped that Perl would clean that mess for me but I doesn't seem so.

Now, do I need to write some sort of copy constructur (*yuck* even the word makes me shudder) and if so how do I do this or is there any other way of nicely solving this mess in a Perl-ish manner?

Thanks in advance for any pointers what to read or hints or code or other forms of enlightenment.

Regards... Stefan
you begin bashing the string with a +42 regexp of confusion


In reply to Deep Copying of Nested Data-Structures by stefan k

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!
  • 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
  • Outside of code tags, you may need to use entities for some characters:
            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?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others studying the Monastery: (10)
    As of 2014-12-28 15:18 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      Is guessing a good strategy for surviving in the IT business?





      Results (182 votes), past polls