dclone#

Produce a structurally independent deep copy of a Perl structure by round-tripping it through the serialiser.

Synopsis#

use Storable qw(dclone);
my $copy = dclone($original);

What you get back#

A reference of the same kind as the input, pointing to a tree whose every scalar, array, hash, and blessed object is a fresh allocation. Modifying $copy never touches $original. Shared references inside the tree remain shared within the copy, and circular references are rebuilt as circular references.

Because dclone runs a full freeze/thaw internally, any blessed object with a STORABLE_freeze / STORABLE_thaw hook has those hooks invoked. This is the only reliable way to clone objects that wrap non-SV state — a PDL piddle with an engine pointer, a tied variable, a file handle — because the hooks give each class a chance to duplicate its backing resource instead of aliasing it.

Examples#

Independent copy of a nested hash:

my $cfg  = { servers => [ { host => "a" }, { host => "b" } ] };
my $copy = dclone($cfg);
$copy->{servers}[0]{host} = "z";
print $cfg->{servers}[0]{host};  # a — original untouched

Clone a blessed object that owns a resource:

my $p = pdl(1, 2, 3);
my $q = dclone($p);
$q->slice("0") .= 99;
print $p->at(0);                # 1 — original piddle unchanged

Edge cases#

  • Argument must be a reference. A plain scalar croaks with Not a reference.

  • A class whose STORABLE_freeze hook dies will propagate that error out of dclone.

  • Depth is bounded by $Storable::recursion_limit (default 512).

Differences from upstream#

  • Equivalent semantics; the internal wire format differs (see freeze). Pinned by t/81-xs-native/Storable/020-dclone.t and t/81-xs-native/Storable/300-dclone-equiv.t.

See also#

  • freeze + thaw — the long-form equivalent of dclone.

  • nfreeze — portable-byte-order producer if you need to ship the clone elsewhere later.

  • store — persist the structure to disk instead of cloning.