Skip to Content
Learning Perl 6
book

Learning Perl 6

by brian d foy
September 2018
Beginner
474 pages
9h 35m
English
O'Reilly Media, Inc.
Content preview from Learning Perl 6

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Think Perl 6

Think Perl 6

Laurent Rosenfeld, Allen B. Downey
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 9781491977675Errata Page