It can be handy to have a clone method so that neighbouring methods are able to make use of a new object based on an existing object. For instance, the code

sub does_something {
    shift unless ref $_[0];
    return $_[0]->merge($_[1]);
}

might want to clone $_[0] so that existing references to it aren’t modified, such as

sub does_something {
    shift unless ref $_[0];
    return $_[0]->clone->merge($_[1]);
}

which would merge $_[1] into a clone of $_[0] instead of modifying $_[0] itself.

Often you’ll need a ‘deep’ clone in those situations, which is left for a separate story. But for a shallow copy, the solution is usually cheap and easy: use new.

sub new {
    my ($proto, %param) = @_;
    my $class = ref $proto || $proto;
    my $self = ref($proto) ? { %$proto } : {};
    %$self = (%$self, %param) if %param;
    return bless $self => $class;
}

That only works for classes where the objects are hashrefs (handling arrayrefs is also easy) and where replacing only the top-level ref is enough.

Advertisements