Question

I can declare an attribut with Moose like this:

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

Is it possible to reset this value to the default value?

Example:

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

Solution

If you do this:

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

then you can do:

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

The combination of lazy and clearer is important here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top