Others have already pointed out how you can use the metaobject protocol to clone objects with Moose. If you know that the object in question is a Moose object, this is a reasonable solution. I want to mention my module Object::Util though. It contains a bunch of utility methods which can be used with Moose objects and other objects too.
use Object::Util; my $cloned_object = $existing_object->$_clone(%extra_parameters);
Object::Util will first check if the existing object has a clone method, and if so, will just call that. After that, it falls back to using the metaobject protocol if it detects the object is Moose- or Mouse-based. Finally as a last resort, if the object is a blessed hashref, it simply does a shallow copy of the hashref and blesses the new hashref.
Object::Util has a bunch of other cool things too, like:
$cloned_object->$_extend({ my_new_method => sub { my $self = shift; print "yay!\n"; }, }); $cloned_object->my_new_method(); # says "yay!"
Note that the methods provided by Object::Util are coderefs in scalar variables, so you call $object->$_method() instead of $object->method(). This is a way to make the methods available for all objects of all classes without polluting UNIVERSAL.
In reply to Re: Moose 'clone' Constructor
by tobyink
in thread Moose 'clone' Constructor
by kcott
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |