Is Perl Dead?

An Introduction to Perl Roles

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

In the previous example the Role::JSON requires the consuming class to have a method named data().

Then you could just call the method defined in the role in your program:

4. Checking if class consumes a role

Because roles are not inherited you cannot use isa() to check if a class consumes a role instead you should use does():

5. Roles without Moose/Moo

Cpan module Role::Tiny allows you to use roles with vanilla OOP not just with Moose or Moo. Like Moose or Moo, Role::Tiny applies strict and warnings to the caller.

Role::Tiny makes available to your role the following method modifiers: before, around and after.

In this example when $self->data is called the around block executes and you get JSON returned.

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

Bibliography