通过自学 Moose,我正在研究与特定硬件接口的 Moose 对象。所述硬件采用许多不同的命令来设置硬件的各种属性,所有形式PROPERTYNAME=VALUE
的设置器和PROPERTYNAME?
获取器(请注意,这些“设置器”和“获取器”位于硬件的网络接口上)。我想要做的是创建一个对象,其中硬件的所有这些属性都使用类似属性的接口来实现。由于获取和设置各种属性对所有属性都采用相同的形式,有没有办法从这些属性的列表中自动生成 setter 和 getter?
IE:而不是这样:
Package MyHardware;
use Moose;
has property1 => (
'is' => 'rw',
'reader' => 'set_property1',
'writer' => 'get_property1',
);
has property2 => (
'is' => 'rw',
'reader' => 'set_property2',
'writer' => 'get_property2',
);
# ...
has propertyN => (
'is' => 'rw',
'reader' => 'set_propertyN',
'writer' => 'get_propertyN',
);
有什么我可以这样做的:
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");
},
);
编辑:这就是我想要发生的事情:
# CALLER:
my $hw = MyHardware->new();
$hw->property1('foo');
print $hw->property2 . "\n";
和“引擎盖下”:
$hw->property1('foo');
# Becomes
sub { return $hw->_send_command('property1=foo'); }
# And
$hw->property2();
# Becomes
sub { return $hw->_send_command('property2?'); }