Hello,

I'm new to Moose and new to OO programming in general.  I apologize in
advance if I mangle language.

In the code attached below, I set up the class Bar that has an arrayref
attribute.  I have a class Foo that has a Bar attribute, foos, and an ifoo
attribute that should point within foos to the element of interest.  I would
like to set up a default behavior where:

my $a = Foo->new(foos=>[0, 1,2]);   sets the first element of foos to the
array ref [0,1,2].  ifoo should be 0 at this point
my $b = $a->foos();                         sets $b to the ifoo element of
foos
$a->foos([3,4,5])                              sets the ifoo element to
array ref [3,4,5];

99   times out of 100     ifoo will be zero and the first element of foos
will be of interest
100 times out of 10000 I'll need to be able to set ifoo to nonzero and
access other elements.  I'm somewhat attached to Bar of the if and when I
add other methods that operates on _bars (foos).   maybe I need to muscle
ifoos into Bar...?

I tried a trigger and failed.

Moose is a powerful drug.

Demian

{
  package Foo;
  use namespace::autoclean;
  use Moose;

  has 'ifoo'  ,    is => 'rw', isa => 'Int' , default => 0;
  has 'foos' => (
                    is      => 'rw',
                    isa     => 'Bar',
                    handles => {
                                add_foos => 'add_bars',
                                get_foos => 'get_bars',
                                set_foos => 'set_bars',
                              count_foos => 'count_bars',
                               },
                    builder  => '_build_foo',
                    trigger  => \&_trigger_foos,
                    lazy     => 1,
                 );

  sub _build_foo{
    return Bar->new();
  }


  sub _trigger_foos
  {
    my $self = shift;
    my $new  = shift;
    if ($new)
    {$self->add_foos($new)}
    else
    {return ($self->get_foos($self->ifoo))};
  }

  __PACKAGE__->meta->make_immutable;
}

{
  package Bar;
  use namespace::autoclean;
  use Moose;

  has '_bars'  =>  (
                    traits   => [ 'Array' ],
                    is       => 'rw',
                    isa      => 'ArrayRef',
                    default  => sub{[]},
                    init_arg => undef,
                    handles  =>
                      {
                        add_bars => 'push',
                        get_bars => 'get',
                        set_bars => 'set',
                        all_bars => 'elements',
                      count_bars => 'count',
                      },
                   );

  __PACKAGE__->meta->make_immutable;

}

use Modern::Perl;
my $a = Foo->new();
#my $a = Foo->new(foos=>[[0,0,0]]);
#my $a = Foo->new(foos=>Bar->new(_bars=>[[0,0,0]]));
$a->add_foos([0,0,0]);
$a->add_foos([1,1,1]);

my $aa = $a->get_foos(0);
my $bb = $a->foos();

use Data::Dumper;

print Dumper $aa;
print Dumper $bb;

1;

Reply via email to