将属性重置为默认值

时间:2013-05-24 19:07:24

标签: perl attributes moose

我可以像这样用Moose声明一个属性:

has 'attr' => (is => 'rw', isa => 'Int', default => 10);

是否可以将此值重置为默认值?

示例:

$obj->attr(5); # sets attr to 5
$obj->_reset_attr;
print $obj->attr; # will print 10

1 个答案:

答案 0 :(得分:6)

如果你这样做:

has 'attr' => (
  is => 'rw',
  isa => 'Int',
  lazy => 1,
  default => 10,
  clearer => '_clear_attr',
);

然后你可以这样做:

my $obj = Class->new;
print $obj->attr; # 10
$obj->attr(5);
print $obj->attr; # 5
$obj->_clear_attr;
print $obj->attr; # 10

lazyclearer的组合非常重要。