lapointd has asked for the wisdom of the Perl Monks concerning the following question:
I find in a number of classes, it is necessary to add a copy function like this (in the object package)...
This is obviously a bit awkward and non-intuitive. What I would really like to do is this, at the application level: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; }
...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!).%copy=%original; # DOES NOT WORK
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!)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Copying Objects
by merlyn (Sage) on Jul 16, 2003 at 18:08 UTC | |
by lapointd (Initiate) on Jul 17, 2003 at 12:19 UTC | |
by merlyn (Sage) on Jul 17, 2003 at 15:09 UTC | |
|
Re: Copying Objects
by edan (Curate) on Jul 17, 2003 at 10:43 UTC | |
by lapointd (Initiate) on Jul 17, 2003 at 12:25 UTC |