Re: Accessor methods questions

[email protected] (Michael Ludwig)
Newsgroups perl.moose
Message-ID <20110821210830.GF1552@Dago>
Moin Gunnar!

Gunnar Strand schrieb am 21.08.2011 um 22:27 (+0200):

> has 'weight' => (
> is => 'ro',
> writer => '_set_weight',
> );

> 1. The above gives me the impression that the accessor method
> *replaces*(i.e., renames) the accessor methods.

By default, there would be weight() acting as getter/setter (or
reader/writer). By specifying "_set_weight" for the writer, you'll
get weight() as a getter and _set_weight() as a writer.

> What is not clear is how accessor write methods store the value if I
> have
> 
> "foo => (is => 'rw', writer => 'set_foo')"

They store it in $self->{foo} because that's the name of the property.

> 2. The above example in the manual shows a way to make an attribute
> "publicly readable, but privately settable", but I don't see how the
> "_set_weight" method can store the weight value?

Basically:

  my $self = shift;
  $self->{weight} = shift;

I didn't understand all of your questions, so my answer might not help
you. Maybe if you run this little script:

          \,,,/
          (o o)
------oOOo-(_)-oOOo------ demo.pl ----
package Bla;
use Moose;
has 'blub', is => 'rw', writer => '_set_kram';
has 'blog', is => 'rw';
no Moose; # without this line left-over symbols in the symbol table

package main;
use Data::Dumper;
use feature 'say';
say for sort keys %Bla:: ; # print package symbol table keys
say '-' x 66;
my $bla = Bla->new( blub => 99, moin => 88 );
# "moin" ignored, not a registered attribute
# $bla->blub(44); # read-only
print Dumper $bla;
$bla->_set_kram(44);
print Dumper $bla;


You can see that in addition to "blub" and "blog", a entry "_set_kram"
is generated in the symbol table. Just one subroutine in addition.
And $bla->blub( $val ) will fail with "Cannot assign a value to a
read-only accessor".

-- 
Michael Ludwig
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.