Bram Vanroy Bram Vanroy - 3 years ago 61
Perl Question

Dynamically generate writer/reader from attribute names in Moose

In Moose we can put restrictions on instance attributes or add getters/setters like so:

has 'color' => (
is => 'rw',
isa => 'Str',
writer => '_set_color',
);


My question is, is there a way to do this dynamically for an array of elements? It's possible to do something like this:

has ['color', 'temperature', 'size'] => (
is => 'rw',
isa => 'Str',
);


But is there a way to create for each of these items its own writer (or reader), e.g.
_set_color
,
_set_temperature
,
_set_size
? I tried to see if the following yielded any insight, but it returned an error


bad accessor/reader/writer/predicate/clearer format, must be a HASH
ref


has ['color', 'temperature', 'size'] => (
is => 'rw',
isa => 'Str',
writer => sub {
print Dumper(\@_);
return;
);


What I am hoping to get is something like (which doesn't work):

has ['color', 'temperature', 'size'] => (
is => 'rw',
isa => 'Str',
writer => "_set_$_";
);


I need custom writers, so just going for the ones provided by Moose does not work for me.

Answer Source

has isn't magic. It's just a subroutine call. So something like this should work (untested):

for (qw[colour temperature size]) {
  has $_ => (
    is     => 'rw',
    isa    => 'Str',
    writer => "_set_$_",
  );
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download