my $copy = bless { %$self }, ref $self;
in @chorba's answer is insufficient. It will only clone the first layer. Any references stored in $self
will not be cloned. The consequences of this is...
$obj->{ponies} = [qw(Dash Sparkle Jack)];
$clone = $obj->clone;
push @{$clone->{ponies}}, "Pinkie";
print join ", ", @{$obj->{ponies}}; # Dash Sparkle Jack Pinkie
You might not have any references now, but you probably will later. Or somebody else will stick one into your object. Or they'll subclass and add one.
You can write a deep cloning routine, but it's not simple. I would highly recommend using Clone. It has no dependencies and so you can simply copy Clone.pm into your project.
The other alternative is Storable::dclone, mentioned by @Zaid, which has been in core for a long time.
No matter what you use, providing a clone method on your class is the right thing to do, even if it's just a wrapper around Clone or Storable::dclone. This will shield the user of your object from the details of how your object is cloned.