As a training for Musa himself, I am working on a Moose object that interacts with certain equipment. Mentioned hardware accepts several different commands that set different hardware properties, all forms of PROPERTYNAME=VALUE for the setter and PROPERTYNAME? for the recipient (note that these "setters" and "getters" are in the network interface to the equipment). I want to create an object in which all these hardware properties are implemented using the attribute interface. Since getting and setting various properties takes the same form for all properties, is there a way to automatically generate setters and getters from a list of these properties?
IE: Instead:
Package MyHardware; use Moose; has property1 => ( 'is' => 'rw', 'reader' => 'set_property1', 'writer' => 'get_property1', ); has property2 => ( 'is' => 'rw', 'reader' => 'set_property2', 'writer' => 'get_property2', );
Is there something I can do like this:
Package MyHardware; use Moose; attributes => ( 'is' => 'rw', 'names' => [qw/property1 property2 ... propertyN/], 'reader' => sub { my $self = shift; my $property = shift; return $self->_send_command("$property?"); }, 'writer' => sub { my $self = shift; my $property = shift; my $value = shift; return $self->_send_command("$property=$value"); }, );
EDIT: Here is what I want:
# CALLER: my $hw = MyHardware->new(); $hw->property1('foo'); print $hw->property2 . "\n";
And "under the hood":
$hw->property1('foo');
source share