Classes

Classes are the “cookie cutters” that build objects. Just as a module groups subroutines in a package, a class groups methods in a package. Classes can also contain subroutines, submethods, and multimethods. However, classes are significantly different from modules, primarily because they construct objects. Objects don’t just define functionality, they also hold data. In Perl 5 objects were simply hashes (or arrays, or . . . ) bestowed with special powers by bless. Perl 6 objects can still be simple blessed data structures, but the default is now an object that hides the details of its internal representation—a true opaque object.

Attributes

Attributes are the data at the core of an opaque object. Other languages have called them instance variables, data members, or instance attributes. Attributes are declared with the has keyword, and generally have a “.” after the sigil:

class Heart::Gold {
    has int $.length;
    has int $.height is rw;
    has @.cargo;
    has %.crew;
    ...
}

Attributes aren’t directly accessible outside the class, but inside the class they act just like ordinary variables:

print $.length;
$.length = 140;

Attributes also automatically generate their own accessor method with the same name as the attribute. Accessor methods are accessible inside or outside the class. By default, accessors are read-only, but the is rw property marks an accessor as read/write.

$value = $obj.height; # returns the value of $.height
$obj.height = 90;     # sets the value of $.height

Methods

Methods ...

Get Perl 6 and Parrot Essentials, Second Edition 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.