http://qs321.pair.com?node_id=126160


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.