This entry will focus on creating and using classes in Perl 6. Perl 6’s class system greatly expands on the approach of Perl 5 in many ways, a few of which are giving a standard new method and providing an approach for easily declaring attributes on a class.
Here is a very simple example of a Perl 6 class:
This example shows a few basic concepts. First there is the new class keyword. Named classes can easily be declared in one of two ways. The example above, with curly braces, is useful when defining more than one class in a file or providing for some code to execute outside of the scope of the class when loading. Without the curly braces is also legal, however it means that the rest of the file is the class definition.
Additionally, this shows our first attribute, name. The name attribute is defined as being of type Str. The twigil ‘.’ in this case indicates that this attribute should have a public accessor. In this case that accessor is read-only because we did not define it otherwise (see below).
The eat and sleep method were also defined. The sleep method uses the name attribute on the class in the string that it says. It can do this without using $self because $. implies the object the method was invoked on. So, the eat method could have also been rewritten like it is for the sleep method.
Instantiating new objects of type Animal and using their methods is simple:
A more complicated example is below. In this one two more classes, ‘Dog’ and ‘Tail’, have been defined:
The Dog class has a couple new interesting additions. The first thing to notice is that Dog inherits from Animal via the is keyword on the first line. The tag attribute is defined as ‘rw’. This means that public accessors for both acquiring and mutating the value of the tag are provided. The tail attribute has a ‘!’ as a twigil. This twigil indicates that no public accessors should be defined. However, an instance of the Dog class delegates to the tail attribute when the wag method is invoked upon it. This means that when someone calls $a_dog.wag they are really calling wag on $a_dog’s $!tail. Delegation is a very handy way to improve code reuse, Perl 5 developers who use Møøse should be familiar with it. Finally the tail also has a default value of a new Tail object.
This new class can be easily used like the following example:
However, what if we didn’t want to use the simple Tail class for our dog’s tail. We could pass in an object of another class that had a wag method on it like so:
That pretty much wraps up this entry on Perl 6’s class system. The system includes many more powerful features that should be covered at a later date.
Further Reading: