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;

In reply to Private Attributes in Moose by musiKk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.