📘 Class attributes in Perl 6

📘 Class attributes in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.


Class data variables are called attributes. They are declared with the has keyword. An attribute’s scope is defined via its twigil. As usual, the first character of the twigil indicates the type of the container (thus, a scalar, an array, or a hash). The second character is either . if a variable is public or ! for the private ones. An accessor will be generated by a compiler for the public attributes.

class Cafe {
    has $.name;
    has @!orders;
}

To create or instantiate an object of the class X, the constructor is called: X.new(). This is basically a method derived from the Any class (this is one of the classes on the top of the object system in Perl 6).

my $cafe = Cafe.new(
    name => "Paris"
);

At this point, you can read public attributes.

say $cafe.name;

Reading from $.name is possible because, by default, all public fields are readable and a corresponding access method for them is created. However, that does not allow changing the attribute. To make a field writable, indicate it explicitly by adding the is rw trait.

class Cafe {
    has $.name is rw;
    has @!orders;
}

my $cafe = Cafe.new(
    name => "Paris"
);

Now, read and write actions are available.

$cafe.name = "Berlin";
say $cafe.name;

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code