Learned monks, I am writing a very abstract and challenging object-oriented application in Perl and I've hit the same problem a few times. It deals with the copying of objects...

I find in a number of classes, it is necessary to add a copy function like this (in the object package)...

sub copy { my ($old)=@_; my $new_step=pathstep->new(); foreach my $key (keys %{$old}) { # copy all attributes and values $new_step->{$key}=$old->{$key}; } return $new_step; }
This is obviously a bit awkward and non-intuitive. What I would really like to do is this, at the application level:
$copy=$original; # DOES NOT WORK
...except all that does is copy the reference, not the underlying data structure. Changes to $copy show up in $original. Another try on the problem is:
%copy=%original; # DOES NOT WORK
...this complains in %copy being an unblessed reference. If you bless %copy in other than the proper module, it thinks it is the wrong kind of object (which can cause strange problems if the access functions are similar!).

It isn't a show stopper or anything - I essentially have it working - it just seems like there should be better way for future endeavors. It gets a bit more complicated when the copy operation is multi-layer (deep copies of objects within objects). The extra code just seems like an invitation to error.

Thanks in advance for your meditations.

(Hmmm, if I could overload operators, I would be in heaven!)


In reply to Copying Objects by lapointd

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.