Declaring a variable belonging to a user-defined class in Perl 6

When I declare a variable whose value belongs to an inline class, I simply write

my Int $a; 

But when I want to use a custom class, I have to use Classname.new .

 my class House { has $.area is rw; } my $house1 = House.new; $house1.area = 200; say $house1.area; 

So, my naive question is: what is the reason for this difference? Why can't we just write my House $house1 ?

My ultimate goal is to use an array whose values ​​are instances of a user-defined class. How can I do the following correctly?

 my @houses ...; @houses[10].area = 222; 
+7
perl6
source share
3 answers

my House $a does the same as my Int $a . This limits the values ​​you can insert into it. If you look at the contents of a variable, you get an object like this constraint.

There is a trick you can use, so you don’t need to repeat the House bit: my House $a .= new , which is equivalent to my House $a = House.new .

To get back to your question: yes, you can do this with some problems:

 class House { has $.area; multi method area(House:U \SELF:) is raw { (SELF = House.new).area } multi method area(House:D:) is raw { $!area } } my House @houses; @houses[2].area = 42; say @houses # [(House) (House) House.new(area => 42)] 

We create two candidates for the access method: one accepts an object of type undefined, and the other an instance of the object. The first modifies its caller (provided that it is a container that can be installed), and then calls an instance of the method. I leave this as an exercise for the reader to turn this into an Attribute trait.

+12
source share

When you write my Int $a; , you will have a variable of type Int , but without a value or even a container. The specific value of $a will be (Int) .

Same thing with my House $house; - you get the value (House) .

In your case, you must initialize the elements of the array with some value of "Home". For example:

 my @houses = House.new() xx 11; @houses[10].area = 222; 
+2
source share

I think you are missing the part that the compiler does for you. When you have a literal number, the parser recognizes it and builds the desired numerical object for it. There is a virtual and invisible Int.new() that already happened for you in rakudo / src / Perl6 / Actions.nqp . It is at the NQP level, but it is the same idea.

+2
source share

All Articles