A role in Perl is essentially
A role provides a piece of functionality which can be composed into (or applied to) any class (which is said to consume the role). A role cannot be inherited but may be consumed by another role.
A role may also require consuming classes to implement some methods instead of implementing the methods itself (just like interfaces in Java or C#).
Perl does not have built-in support for roles but there are CPAN classes which provide such support.
package Chatty;
use Moose::Role;
requires 'introduce'; # a method consuming classes must implement
sub greet { # a method already implemented in the role
print "Hi!\n";
}
package Parrot;
use Moose;
with 'Chatty';
sub introduce {
print "I'm Buddy.\n";
}
Use if your OO system does not provide support for roles (e.g. Class::Accessor
or Class::Tiny
).
Does not support attributes.
package Chatty;
use Role::Tiny;
requires 'introduce'; # a method consuming classes must implement
sub greet { # a method already implemented in the role
print "Hi!\n";
}
package Parrot;
use Class::Tiny;
use Role::Tiny::With;
with 'Chatty';
sub introduce {
print "I'm Buddy.\n";
}