oop - Perl: How to deep copy a blessed object? -
i'm looking deep (at point, shallow may suffice) copy of blessed object.
foo class
package foo; our $foo = new foo; # initial run sub new { $class = shift; $self = {}; bless $self, $class; return $self; }
main program
use foo; $copy = $foo::foo; # instead of creating ref, want deep copy here $copy->{bar} = 'bar';
bar
appears in both $foo::foo
, $copy
. realize create copy of object setting $copy = { %{$foo::foo} }
, no longer blessed; additionally, work simple data structures (right not issue). way copy way , bless after (eg $copy = bless { %{$foo::foo} }, q{foo};
)?
i'm trying avoid using moose, clone, or other non-core modules/packages, please keep in mind when replying. bolded stands out more :)
the copying should part of api. user of module never know special actions required upon creation of new object (consider registering each object in my
hash in package).
therefore, provide clone
method objects. inside it, can use dirty tricks like:
sub clone { $self = shift; $copy = bless { %$self }, ref $self; $register{$copy} = localtime; # or whatever else need new object. # ... return $copy; }
Comments
Post a Comment