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


in reply to Changing the Class Name of a Moose Instance

use v5.14; use Moose (); sub with_traits_and_fancy_schmancy_name { my ($name, $base, @roles) = @_; return $base unless @roles; return 'Moose::Meta::Class'->create( $name, superclasses => [$base], roles => \@roles, )->name; } package Person { use Moose; has name => (is => 'ro', isa => 'Str'); sub add_numbers { my $self = shift; my $sum; $sum += $_ for @_; return $sum; } }; package Inumerate { use Moose::Role; around add_numbers => sub { confess "I'm no good at maths"; }; }; my $bob = with_traits_and_fancy_schmancy_name( 'Idiot', 'Person' => qw( Inumerate ), )->new(name => 'Robert'); $bob->add_numbers(1, 2, 3);

Update: previously I didn't include a very good example usage.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Replies are listed 'Best First'.
Re^2: Changing the Class Name of a Moose Instance
by jandrew (Chaplain) on Oct 03, 2012 at 17:02 UTC

    Thanks++, that works.

    Update: I just ran the updated example and I like the 'confess' output that includes Idiot::add_numbers('Idiot=HASH(0x337cf38)', 1, 2, 3). Nice touch