Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: Changing the Class Name of a Moose Instance

by tobyink (Abbot)
on Oct 03, 2012 at 16:45 UTC ( #997097=note: print w/ replies, xml ) Need Help??


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'


Comment on Re: Changing the Class Name of a Moose Instance
Download Code
Re^2: Changing the Class Name of a Moose Instance
by jandrew (Hermit) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://997097]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2015-07-03 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (48 votes), past polls