Chapter 12. Classes

A class is the blueprint for an object and manages an object and its behavior. It declares attributes to define what an object will store and methods to define how an object can behave. Classes model the world in a way that makes it easier for your program to do its job.

I’m mostly going to ignore object-oriented analysis and design. This chapter is about the mechanism of classes and objects. The examples show you how things work and do not endorse a particular way. Use what works for your task and stop using that when it doesn’t.

Your First Class

Declare a class by giving it a name and a Block of code:

class Butterfly {}

That’s it! It looks like this class is empty, but it’s not. You get much of its basic behavior for free even though you don’t see it explicitly. Try calling some methods on it. You can see that it derives from Any and Mu and that you can create new objects:

% perl6
> class Butterfly {}
(Butterfly)
> Butterfly.^mro
((Butterfly) (Any) (Mu))
> my $object = Butterfly.new
Butterfly.new
> $object.^name
Butterfly
> $object.defined
True

You can have as many of these class declarations as you like in one file:

class Butterfly {}
class Moth {}
class Lobster {}

These types are available to your program as soon as they are defined in the code, but not before. If you try to use one before you define it you get a compilation error:

my $butterfly = Butterfly.new;  # Too soon!

class Butterfly {};  # Error: Illegally post-declared type

Instead of defining all of your classes ...

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.