musiKk has asked for the wisdom of the Perl Monks concerning the following question:
Hello fellow Monks,
recently I needed to keep some internal state between two method calls to a Moose object. I know now that the way to do that is to create an attribute with a name with a leading underscore. However I tried it like so:
has priv_attr => ( is => 'rw', isa => 'Str', reader => '_priv_attr', writer => '_priv_attr' );
I used this attribute in a method:
sub do_stuff { my $self = shift; $self->_priv_attr( 1 ); $self->_priv_attr; }
However, upon calling the method do_stuff the following error occurs:
Attribute (priv_attr) does not pass the type constraint because: Valid +ation failed for 'Str' with value undef at ./test.pl line 22 Foo::do_stuff('Foo=HASH(0x8d02c18)') called at ./test.pl line +28
So setting kinda works (in the sense that it doesn't fail) but the value is undefined afterwards. Is there some logic in that? To me it feels like a bug but I'm not very experienced in Moose.
Copy and paste ready code is here:
#!/usr/bin/env perl use warnings; use strict; { package Foo; use Moose; has priv_attr => ( is => 'rw', isa => 'Str', reader => '_priv_attr', writer => '_priv_attr' ); sub do_stuff { my $self = shift; $self->_priv_attr( 1 ); $self->_priv_attr; } 1; } Foo->new->do_stuff;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Private Attributes in Moose
by ikegami (Patriarch) on Jul 22, 2011 at 21:14 UTC | |
by musiKk (Initiate) on Jul 23, 2011 at 16:10 UTC | |
by ikegami (Patriarch) on Jul 23, 2011 at 22:40 UTC | |
|
Re: Private Attributes in Moose
by choroba (Cardinal) on Jul 22, 2011 at 21:17 UTC |