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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|