๐Ÿ“˜ Class attributes in Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s