develooper Front page | perl.moose | Postings from April 2015

Re: Moose n00b question about writer / reader

Thread Previous | Thread Next
From:
Kent Fredric
Date:
April 20, 2015 02:53
Subject:
Re: Moose n00b question about writer / reader
Message ID:
CAATnKFDoGXH=prNXVCo5dNkywWeVeiif1jB5-rX+Bjk0wF-ekg@mail.gmail.com
On 20 April 2015 at 07:00, Andrew Hicox <andrew@hicox.com> wrote:

> This seems like I’d just need to declare a writer sub for the attribute,
> do my logic in there, then set the attribute value or throw an error, right?
>
> Why doesn't this work?
>
> package Bogus {
> use Moose;
> has ‘value’, is => “rw”, writer => “_value”, isa => “Num”;
> sub _value {
> my ($self, $value) = @_;
> ## insert some logic here
> $self->value($value);
> return(1);
> }
> }
>
> use Bogus;
> my $a = new Bogus(value => 1);
>
>
The initial mistake I believe you made was thinking that the argument to
writer was intended to be a "I'll create this sub, Moose can use it".

Whereas that argument in this case is "Moose, create me a writer called
_value".

So the RHS of that token is intended for more external interfaces, eg:

---

has value => ( is => 'rw', writer => "set_value" , reader => "get_value");
...
$object->set_value(  $arg );
$object->get_value(); # returns $arg

---


so:

$writer_sub -> internal attribute store
$reader_sub <- internal attribute store

$writer_sub and $readersub can sometimes be the same sub, which is the
default case with "is => rw".

For comparion, see:  "is => raw", where $object->value won't exist.


-- 
Kent

*KENTNL* - https://metacpan.org/author/KENTNL

Thread Previous | Thread Next


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