If the role has been applied to the instance (rather than its class), then you can certainly remove all such roles by reblessing it back into its original class:
$class->meta->rebless_instance($object);
But this sounds like a bad idea.
Perhaps instead of adding and removing roles you should consider using delegation.
class Teacher {
method teach () { ... }
}
class ClassRoom {
has teacher => (
is => 'rw',
handles => ['teach'],
clearer => 'vacate',
);
}
my $room1 = ClassRoom->new;
eval {
$room1->teach; # dies (no teacher!)
};
# Instead of adding a role,
# give the classroom an object
# that it can delegate to...
#
$room1->teacher( Teacher->new );
$room1->teach; # ok!
# Instead of removing the role,
# remove the object that's being
# delegated to...
$room1->vacate;
eval {
$room1->teach; # dies (no teacher!)
};
Roles are awesome and it's tempting to use them for everything, but maybe delegation is something more appropriate for the problem you're trying to solve. Step back and explain your wider problem and we might be able to give you other ideas of how to approach it.
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
|