Reputation: 28465
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.
Upvotes: 2
Views: 63
Reputation: 69274
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_$_",
);
}
Upvotes: 4