Chapter 13. Roles

Roles are mixins that augment your class as if their contents were defined in it. Once defined their source is effectively forgotten (unlike a parent class). You can use roles to change classes, make a new class from an existing one, and enhance single objects. They are a more flexible and often a better solution than inheritance. These are for code reuse whereas classes are for managing objects.

Adding Behavior to Classes

Construct an empty Butterfly class. You can give arguments to .new even though no attribute receives their value:

class Butterfly {}
my $butterfly = Butterfly.new: :common-name('Perly Cracker');

Now give your butterfly a name. Should that be part of the Butterfly class? A name isn’t the object. Hamadryas guatemalena is the name of a butterfly. So are Guatemalan Cracker, Calicó, and Soñadora común. Those are all names for the same butterfly.

Note

Ultimately the code you write has to operate within the framework of the language. The syntax sometimes lets you cognitively separate things.

A name is not a more specific version of something the class already does and it’s not limited to butterflies or butterfly-like things. Many dissimilar things can have a common name—animals, cars, food. Not only that, but different people, cultures, or even sections of your office may choose different names. This fact does not define your thingy or its behavior. It’s not something that makes a butterfly what it is.

Create a role that contains everything you need for a common ...

Get Learning Perl 6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.