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

Re: Object::Clone a simple class providing a cloning method

by premchai21 (Curate)
on Nov 18, 2001 at 23:54 UTC ( #126160=note: print w/replies, xml ) Need Help??


in reply to Object::Clone a simple class providing a cloning method

The problem here is that if your object contains references to other objects, the other objects get cloned too; if that is what you want, then Storable already provides dclone. You could copy only unblessed references by doing something like this:
sub sclone { while (defined(my $what = shift)) { for my $r (ref $what) { ($r eq 'ARRAY') && return [map { sclone $_ } @$r]; ($r eq 'HASH') && return do { my %s = map { $_ => sclone ($$r{$_}) } keys %$r}; \%s; }; ($r eq 'SCALAR') && return do { my $s = $$r; \$s; }; return $r; } } }
This can still cause problems, though... suppose you have a reference to a class variable? Now it points to an anonymous scalar, which isn't what you want. But suppose you have a reference to an anonymous scalar, and you just copy the reference directly? Now you have a pointer to the same anonymous scalar, which isn't what you want. There's no real way programatically to tell the difference, unless it's specified in the class somewhere... and if it is, then IMHO the class might as well have its own clone routine.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://126160]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (3)
As of 2021-11-27 03:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?