http://www.perlmonks.org?node_id=997078

jandrew has asked for the wisdom of the Perl Monks concerning the following question:

I have been searching unsuccessfully for a way to change the class name of a Moose instance. Most specifically when I am composing Moose classes on the fly using Moose::Util 'with_traits'. Any helpful suggestions are appreciated.

The initial use case for me is to make the confess output from Carp more readable. I have included demonstration code below.

package MyClass; use Moose; has 'name' => ( is => 'ro', writer => 'set_name', predicate => 'has_name', ); no Moose; __PACKAGE__->meta->make_immutable; package Respect; use Moose::Role; use Carp qw( cluck ); sub get_respectful_name{ my ( $self, ) = @_; if( $self->has_name ){ return $self->name . " - San\n"; }else{ cluck "No name is available"; return undef } } no Moose::Role; use Moose::Util qw( with_traits ); use Smart::Comments '###'; my $business_associate = with_traits( 'MyClass', ( 'Respect', ), )->new(); print "Hello " . $business_associate->get_respectful_name . "\n"; $business_associate->set_name( 'Miyagi' ); print "Hello " . $business_associate->get_respectful_name . "\n"; 1;

The output is as follows

No name is available at MooseClassName.pl line 22 Respect::get_respectful_name Moose::Meta::Class::__ANON__::SERIAL::1= HASH(0x3591540)') called at MooseClassName.pl line 39 Use of uninitialized value in concatenation (.) or string at MooseClassName.pl line 39. Hello Hello Miyagi - San

The goal would be to set -Moose::Meta::Class::__ANON__::SERIAL::1- to something more human readable.

It seems there might be other use cases for this but as a minimum the 'meta' capabilities of Moose have spoiled me into believing that all information about an instance is accessible and mutable as needed. I just can't seem to figure out how.

Update: spelling corrections