Hello Andrew,
you write:
> Apologies if this is a dumb question, but I have repeatedly tried to
> understand this section of the documentation, and I need some help:
>
>
http://search.cpan.org/~ether/Moose-2.1404/lib/Moose/Manual/Attributes.
> pod#Accessor_methods
>
> I want to create a class that has some attributes. However, there’s
> some logic that needs to be executed when setting values on these
> attributes. In some cases, I’ll need to throw an error like “you can’t
> set that value on this object attribute”, I also need to be able to
> modify the value on the way into the object sort of like a DECODE()
> statement in SQL, etc.
You'll want to scroll half a dozen screenfuls downward on the same page
and check out the section titled "Triggers". These can be used to do
exactly the things you want.
Setting writer / reader, on the other hand, is just providing names to
the accessor routines which Moose creates automatically for you.
> 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”;
make that trigger => "_value"
> sub _value {
> my ($self, $value) = @_;
...you'll get ($self,$value,$previous_value) = @_;
> ## insert some logic here
Your logic can check and modify $current_value, and if changed, pass it
to the writer (again), or even reinstate the previous value.
> $self->value($value);
> return(1);
> }
> }
>
>
> use Bogus;
> my $a = new Bogus(value => 1);
>
> Can what I’m trying to do even be done in Moose?
> again, sorry for the dumb question. I’m quite sure I’ve just missed
> something in my understanding.
I'm also a Moose beginner (more or less) and know this feeling very
well. There's a lot of stuff to read, and I was lucky to have a gentle
introduction at our Perl monger's meeting.
I have never tried the more sophisticated methods to achieve your goal:
declare how to check your value as described in
`perldoc Moose::Manual::Types`: type constraints can valuate the input
against the properties of a custom class, and coercion can modify the
value on the fly.
--
Cheers,
haj