The correct way to create a Moose object from another Moose object?

What is the correct way to instantiate from another Moose object? In practice, I have seen this many times:

$obj->meta->name->new() $obj->new() ## which has been deprecated and undeprecated (blessed $obj)->new() -- and, its bastard variant: (ref $obj)->new() $obj->meta->new_object() 

And what if you have traits ? Is there a transparent way to support this? Do any of these actions with anonymous classes ?

+7
perl moose
source share
1 answer

From your choices, $obj->meta->name->new() or (blessed $obj)->new() are the safest.

Implemented implementation methods, you create an anonymous subclass and apply roles to this subclass and restart the instance in this subclass. This means that any of these solutions will work perfectly with features. Perl does not have truly anonymous subclasses (each package must have a namespace), Moose works around this, creating a name in a common namespace for anonymous classes.

If you took a second to try the sample code, you will see it in action.

  $perl -Moose -E'with q[MooseX::Traits]; package Role; use Moose::Role; package main; say Class->with_traits(q[Role])->new->meta->name' MooseX::Traits::__ANON__::SERIAL::1 

Hope this helps.

+6
source share

All Articles