Hi Matthew,

given this fragment
>
> has 'mylist' => (isa => 'ArrayRef', default => sub { [] });
>
> at a point in my code later on I want to clear it to reset it so I do
>
> $self->mylist([]);
>
> Is there anyway I could invoke the default? Something like
>
> $self->mylist()->default();
>

That would require $self->mylist returning an object rather than an
ArrayRef. Obviously that's possible -- you could implement 'mylist' as an
object which contains elements and has it's own default() method -- however,
if you wanted to keep it as an ArrayRef then one way would be to create a
builder for your attribute, then implement your own reset_mylist() method
which resets the attribute using that builder.


package My::Foo;

use Moose;

has 'mylist',
  is => 'rw',
  isa => 'ArrayRef',
  builder => '_build_mylist';

sub _build_mylist { [ ] }

sub reset_mylist {
  (shift)->{mylist} = _build_mylist()
}

sub print_mylist {
  my $self = shift;
  print @{ $self->mylist } ? join( ", ", @{ $self->mylist } )
                           : "mylist is empty";
  print "\n";
}

package main;

my $o = My::Foo->new();

$o->print_mylist;           # mylist is empty

$o->mylist( [1, 2, 3] );
$o->print_mylist;           # 1, 2, 3

$o->reset_mylist;
$o->print_mylist;           # mylist is empty


If you haven't already then you might want to have a look at:


http://search.cpan.org/~sartak/MooseX-AttributeHelpers-0.14/lib/MooseX/AttributeHelpers.pm


Cheers,

Ian



-- 
Ian Sillitoe
CATH Team -- http://cathdb.info

Reply via email to