A piggy bank of commands, fixes, succinct reviews, some mini articles and technical opinions from a (mostly) Perl developer.

Jump to

Quick reference

Showing posts with label attribute. Show all posts
Showing posts with label attribute. Show all posts

Moose questions

These points are not covered in the Moose documentation:

Question: If you set an attribute in the constructor, does it override the builder?
Answer: Yes, the builder is not run.
Code:
perl -MMoose -le'package Quxx; use Moose; has "qux" => ( is => "ro", builder => "_build_qux" ); sub _build_qux { die "duck" }; package main; my $q = Quxx->new( qux => "cat" ); print "qux = #".$q->qux."#"'
Output:
qux = #cat#

Question: How do you compose a writer subroutine? (aka setter / mutator method).
Answer: You don't need to, Moose creates it for you. Just define it in the attribute and then call it.
Code:
perl -MMoose -le'package Foo; use Moose; has "foo" => ( is => "rw", writer => "_set_foo" ); sub set_foo { "bar" }; sub bar { my $self = shift; $self->_set_foo(2); }; package main; my $f = Foo->new; $f->bar(4); print "foo = #".$f->foo."#"'
Output:
foo = #2#