Is Perl dead? Far from it. Perl is a lively programming language with several new features. To prove this, let’s discuss Perl Roles, which are similar to traits in Smalltalk or an interface in Java.
1. Roles Definition
A role is a set of methods that provide extra behavior to a class. Roles can’t be used independently they need a class to consume them. Roles are a good alternative to inheritance.
2. A sample role
A role is declared in a *.pm file.
3. Consuming a role
4. Checking if class consumes a role
Role::Tiny makes available to your role the following method modifiers: before, around and after.
6. Compositional safety
Roles attempt to guarantee compositional safety. So, if two roles have the same method defined and you try to consume them in the same class, you will get an error message.
Just remember that in order to trigger the error message you need to consume all the roles at once:
7. How to fix method collision
- Implement the methods yourself in your class, thus causing the corresponding role methods to be ignored
- For Moose use the excludes key word
- For Role::Tiny use namespace::clean