in reply to Moose 'clone' Constructor
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Moose 'clone' Constructor
by kcott (Archbishop) on Jul 05, 2018 at 04:18 UTC | |
by tobyink (Canon) on Jul 05, 2018 at 08:29 UTC | |
by kcott (Archbishop) on Jul 05, 2018 at 08:51 UTC | |
by tobyink (Canon) on Jul 05, 2018 at 17:11 UTC | |
by huck (Prior) on Jul 05, 2018 at 06:25 UTC | |
by kcott (Archbishop) on Jul 05, 2018 at 07:34 UTC | |
by Athanasius (Archbishop) on Jul 06, 2018 at 09:44 UTC | |
by kcott (Archbishop) on Jul 06, 2018 at 11:09 UTC | |
|