clone#

Return a deep, independent copy of a Perl value.

Synopsis#

use Clone qw(clone);

my $copy = clone($thing);          # function form
my $copy = clone($thing, 5);       # limit recursion depth
my $copy = $obj->clone;            # method form (class inherits from Clone)

What you get back#

A value of the same kind as the input. The copy is fully independent: assigning into $copy — at any nesting level — never changes $thing.

  • Shared references inside the input are de-duplicated: if two slots pointed at the same referent, the corresponding two slots in the copy point at one fresh clone of that referent, not two separate clones.

  • Circular structures are reproduced with their cycles intact.

  • Weak references (see Scalar::Util::weaken) come out weak in the copy.

  • Tied variables keep their tie; the tie’s internal object is itself cloned.

  • Blessed objects are reblessed into the same package as the original.

Examples#

Basic hash clone — the copy is independent:

use Clone qw(clone);
my $h = { name => 'Alice', tags => [qw(admin user)] };
my $c = clone($h);
push @{ $c->{tags} }, 'guest';
print "@{ $h->{tags} }\n";         # admin user
print "@{ $c->{tags} }\n";         # admin user guest

Shared references stay shared inside the clone:

my $shared = { count => 0 };
my $pair   = { a => $shared, b => $shared };
my $copy   = clone($pair);
$copy->{a}{count} = 42;
print $copy->{b}{count};           # 42  (a and b still point at one hash)
print $pair->{a}{count};           # 0   (original untouched)

Circular structures:

my $a = { name => 'A' };
my $b = { name => 'B', peer => $a };
$a->{peer} = $b;                   # cycle
my $copy = clone($a);
print $copy->{peer}{peer}{name};   # A  (cycle reproduced)

Edge cases#

  • undef clones to undef.

  • A non-reference scalar (42, "hi") clones by value — you get a fresh scalar with the same contents.

  • Code references are shared, not duplicated: the clone points at the same sub.

  • Filehandles and IO objects are cloned but share the underlying file descriptor and file position.

  • The depth argument caps recursion. clone($thing, 0) returns $thing unchanged (refcount bump, no copy). A negative or omitted depth means “unlimited”; the runtime still guards against stack overflow by falling back to an iterative cloner once rdepth passes 4000.

Differences from upstream#

Fully compatible with upstream Clone 0.50.

See also#

  • Storable::dclone — serializer-based deep copy; typically faster for structures 4+ levels deep, slower for shallow ones.

  • Scalar::Util::weaken — create the weak references that clone preserves.

  • Clone::PP — pure-Perl implementation of the same interface.