More about attributes
We started this chapter with the Class attributes, section but some of the features of attributes are closely connected with methods, that's why we made a break and now are able to continue talking about attributes.
Public and private attributes
In the previous code examples, the class attribute was declared with the dot sigil—$.rooms
or $.street
. A dot at that position means that the attribute is public and may be accessed by code that does not belong to the class.
There is another twigil, !
, which makes attributes private. This means that the only way to read or change the value of an attribute is to access it from methods.
Let us return to the House
class and change all the twigils of its methods to !
:
class House { has $!rooms; has $!area; has $!height; }
Creating a house can be done in the same way as before:
my $house = House.new( rooms => 2, area => 100, height => 3, );
However, it is now not possible to read the value of the attributes...