I am trying to learn the Perl 6 object model and succeeded to work my way through a number of Perl 6 object features, including inheritance, roles, submethods and some other slightly more advanced features, but I am repeatedly stumbling on a very basic feature: how to access private attributes within the class?
Consider this very basic class for 3-D dots:
class Dot { has $.x; has $.y; has $!z; method get { return ($!x, $!y, $!z); } }; my $a = Dot.new(x => 23, y => 42, z => 2); say $_ for $a.get;
The output of the above code is:
My understanding is that using the "." twigil for declaring the attribute will create an accessor method making in effect these attributes public outside the class. And indeed, with this, I can easily access the x and y attributes from outside the class (code not shown here above, but something like: say $a.x;).23 42 (Any)
My problem is with the z attribute. Since it is declared with the ! twigil, it cannot be accessed from outside the class. Fair enough, that's precisely what I wanted to test. So that's why I wrote a get accessor method within the class. But it seems that the get function is also not able to read the z attribute, which stubbornly remains undefined (well Any), even if I try to print it from within the class.
I tried various syntax variations (using self, naming the invocant, etc.), but nothing seemed to work, the z attribute remains unaccessible.
Trying to use the z attribute for some calculation in a method declared within the class gives me the following slightly more informative warning:
Use of uninitialized value of type Any in numeric context ...
I guess I must be missing some very simple and basic point, and I went through all the documentation that I could find, but I can't figure out what is wrong with this test. Any idea? Thanks in advance for any clue.
I am using Rakudo * / Perl 6 dated September 2015, so a fairly recent release.
In reply to Private attributes in Perl 6 objects by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |