Search code examples
perlattributesmoose

Reset an attribute to default value


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

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.