develooper Front page | perl.perl6.compiler | Postings from June 2018

[perl #133246] Possible bug in Perl 6 OO

Thread Previous
From:
Zoffix Znet via RT
Date:
June 9, 2018 12:33
Subject:
[perl #133246] Possible bug in Perl 6 OO
Message ID:
rt-4.0.24-3584-1528547584-1500.133246-15-0@perl.org
On Mon, 04 Jun 2018 07:31:40 -0700, richard.hogaboom@gmail.com wrote:
> Attached is an executable file that demos a possible Perl 6 OO bug if 
> attributes and method names are the same.  This includes some compile 
> time errors and an infinite loop.
> 

Thanks for the report, but there's no bug here.

The `has $.foo` attribute syntax is just a shorthand for writing `has $!foo; method foo { $!foo }`.
In other words, the compiler auto-generated an accessor method for you.

When you use `$.foo` syntax inside a method, it's a shorthand for `self.foo`; in other words, it's a
method call.

If you define a method with the same name as the attribute, then it signals to the compiler that you chose
to take care of accessor method yourself.

Also, to return a writeable container, you need to either use `return-rw` instead of plain `return` when
using explicit return, or apply the `is rw` trait to the method, when using implicit return:


    method var1() is rw { return    $!var }
    method var2()       { return-rw $!var }

With that knowledge, you can see why the failing examples fail:

* EXAMPLE 3: You defined a method with the same name as attribute, so it'll function as the accessor. The body
             of that method is empty, so it returns `Nil` and hence the error about trying to assign to `Nil`
* EXAMPLE 4: Again, you defined your own accessor, but now you're also using `$.var` syntax inside, so the method
             infiniloops calling itself over and over. Hence the hang.
* EXAMPLE 5: You've used `return` instead of `return-rw`, so only a readonly value is returned instead of a
             writable container. Hence the error

> but shouldn't there be some type of prohibition/warning?

No, as it's perfectly fine to declare your own accessors. Of course, writing `has $.foo` instead of `has $!foo` is
pointless, in that case, but it serves as a hint to the programmer that it's a public attribute, so I don't think
warning about that is appropriate.

Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About