On Thu, 5 Feb 2009, Ian Sillitoe wrote:
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
This is not right. There's a much simpler way, and it doesn't require
digging into the object's hashref, which is strongly discourage with
Moose.
package Foo;
has 'list' =>
( is => 'rw',
isa => 'ArrayRef',
lazy => 1,
default => sub { [] },
clearer => '_clear_list',
);
my $foo = Foo->new();
$foo->list(); # makes a new arrayref and returns it
$foo->_clear_list;
$foo->list(); # makes a new arrayref and returns it, again
I do second the recommendation to take a look at MX::AttributeHelpers,
though.
-dave
/*============================================================
http://VegGuide.org http://blog.urth.org
Your guide to all that's veg House Absolute(ly Pointless)
============================================================*/