package MyClass; use Moo; sub BUILD { my ( $self, $args ) = @_; my $module = $args->{'number'} % 2 ? 'Odd' : 'Even'; warn "$args->{'number'} $self loading $module"; eval "with '$module'; 1;" or die $@; } 1; #### package Odd; use Moo::Role; warn "Loaded ", __PACKAGE__; sub bar { my ( $self, $foo ) = @_; warn "$foo $self I am Odd"; } 1; #### package Even; use Moo::Role; warn "Loaded ", __PACKAGE__; sub bar { my ( $self, $foo ) = @_; warn "$foo $self I am Even"; } 1; #### #!usr/bin/perl use strict; use warnings; use MyClass; foreach my $foo ( 1 .. 2 ) { print "\n"; my $o = MyClass->new({ number => $foo }); warn "$foo $o->bar"; $o->bar( $foo ); print "\n"; } __END__ #### $ perl test.pl 1 MyClass=HASH(0x118df00) loading Odd at MyClass.pm line 8. Loaded Odd at Odd.pm line 4. 1 MyClass=HASH(0x118df00)->bar at test.pl line 13. 1 MyClass=HASH(0x118df00) I am Odd at Odd.pm line 7. 2 MyClass=HASH(0x11b68e8) loading Even at MyClass.pm line 8. Loaded Even at Even.pm line 4. 2 MyClass=HASH(0x11b68e8)->bar at test.pl line 13. 2 MyClass=HASH(0x11b68e8) I am Odd at Odd.pm line 7. #### package MyClass; use Moo; 1; #### #!usr/bin/perl use strict; use warnings; use MyClass; use Role::Tiny(); foreach my $foo ( 1 .. 2 ) { my $module = $foo % 2 ? 'Odd' : 'Even'; my $class = Role::Tiny->create_class_with_roles( 'MyClass', $module ); my $o = $class->new(); $o->bar( $foo ); } __END__ #### $ perl test.pl 1 MyClass__WITH__Odd=HASH(0x23f5f80) I am Odd at Odd.pm line 8. 2 MyClass__WITH__Even=HASH(0x2442db0) I am Even at Even.pm line 7.