Clone(3pm)

Clone3pm

Recursively copy perl datatypes

Usage

    use Clone 'clone';
    my $data = {
       set => [ 1 .. 50 ],
       foo => {
           answer => 42,
           object => SomeObject->new,
       },
    };
    my $cloned_data = clone($data);
    $cloned_data->{foo}{answer} = 1;
    print $cloned_data->{foo}{answer};  # '1'
    print $data->{foo}{answer};         # '42'

You can also add it to your class:

    package Foo;
    use parent 'Clone';
    sub new { bless {}, shift }
    package main;
    my $obj = Foo->new;
    my $copy = $obj->clone;

Overview

This module provides a clone() method which makes recursive copies of nested hash, array, scalar and reference types, including tied variables and objects.

clone() takes a scalar argument and duplicates it. To duplicate lists, arrays or hashes, pass them in by reference, e.g.

    my $copy = clone (\@array);
    # or
    my %copy = %{ clone (\%hash) };

Examples

Cloning Blessed Objects

    package Person;
    sub new {
        my ($class, $name) = @_;
        bless { name => $name, friends => [] }, $class;
    }
    package main;
    use Clone 'clone';
    my $person = Person->new('Alice');
    my $clone = clone($person);
    # $clone is a separate object with the same data
    push @{$person->{friends}}, 'Bob';
    print scalar @{$clone->{friends}};  # 0

Handling Circular References

Clone properly handles circular references, preventing infinite loops:

    my $a = { name => 'A' };
    my $b = { name => 'B', ref => $a };
    $a->{ref} = $b;  # circular reference
    my $clone = clone($a);
    # Circular structure is preserved in the clone

Cloning Weakened References

    use Scalar::Util 'weaken';
    my $obj = { data => 'important' };
    my $container = { strong => $obj, weak => $obj };
    weaken($container->{weak});
    my $clone = clone($container);
    # Both strong and weak references are preserved correctly

Cloning Tied Variables

    use Tie::Hash;
    tie my %hash, 'Tie::StdHash';
    %hash = (a => 1, b => 2);
    my $clone = clone(\%hash);
    # The tied behavior is preserved in the clone

Limitations

•

Maximum Recursion Depth

Clone uses a recursion depth counter to prevent stack overflow. The default limit is 4000 rdepth units on Linux/macOS and 2000 on Windows/Cygwin. Each nesting level consumes approximately 2 rdepth units, so the effective limits are roughly 2000 nesting levels on Linux/macOS and 1000 on Windows/Cygwin.

When the limit is exceeded, Clone switches to an iterative fallback that preserves deep-copy semantics without stack overflow. This covers arrays, hashes, and all reference types (including deeply nested scalar references). The fallback drives nested containers through a heap-allocated work queue, so its C stack usage does not grow with nesting depth whatever the shape of the data.

Non-clonable types (globs, code references, formats, IO handles) are always shared regardless of depth. Encountering one directly as a container element past the depth limit also emits a warning (one reached through a reference is shared silently, as at any depth). To silence it:

    $Clone::WARN = 0;

You can override the depth limit by passing it as the second argument to clone():

    my $copy = clone($data, 8000);  # allow deeper recursion
•

Filehandles and IO Objects

Filehandles and IO objects are not deep-copied. The clone shares the same underlying filehandle object as the original (reference count is incremented). For DBI database handles, Clone skips opaque XS magic to avoid dangling pointers, but the resulting clone should not be used as a database handle.

•

Code References

Code references (subroutines) are cloned by reference, not by value. The cloned coderef points to the same subroutine as the original.

•

Thread Safety

Clone is not explicitly thread-safe. Use appropriate synchronization when cloning data structures across threads.

Performance

Clone is implemented in C using Perl's XS interface, making it very fast for most use cases.

•

When to use Clone

Clone is optimized for speed and works best with:

•

Shallow to medium-depth structures (3 levels or fewer)

•

Data structures that need fast cloning in hot code paths

•

Structures containing blessed objects and tied variables

•

When to use Storable::dclone

Storable's dclone() may be faster for:

•

Very deep structures (4+ levels)

•

When you need serialization features

Benchmarking your specific use case is recommended for performance-critical applications.

Caveats

•

Cloned objects are deep copies

Changes to the clone do not affect the original, and vice versa. This includes nested references and objects.

•

Object internals

While Clone handles most blessed objects correctly, objects with XS components or complex internal state may not clone as expected. Test thoroughly with your specific object types.

•

Memory usage

Cloning large data structures creates a complete copy in memory. Ensure you have sufficient memory available.

Support

•

Bug Reports and Feature Requests

Please report bugs on GitHub: <https://github.com/garu/Clone/issues>

•

Source Code

The source code is available on GitHub: <https://github.com/garu/Clone>

Releases

12 releases since Debian 3.1 (Sarge); the text changed 11 times.

  1. 3.1
  2. 4.0
  3. 5.0
  4. 6.0
  5. 7
  6. 8
  7. 9
  8. 10
  9. 11
  10. 12
  11. 13
  12. Arch

Author

Ray Finch "<[email protected]>"

Breno G. de Oliveira "<[email protected]>", Nicolas Rochelemagne "<[email protected]>" and Florian Ragwitz "<[email protected]>" perform routine maintenance releases since 2012.

From perl-clone 0.51-2 in Arch Linux 2026-11-01. Parsed by carta from the page's man source.