cellofan has asked for the wisdom of the Perl Monks concerning the following question:
small code:
has 'id' => ( is =>'ro', isa => 'Int', required => 1, builder => '_labelling', init_arg => undef, ); sub _labelling { $N++ } has 'verlet' => ( is =>'rw', isa => 'ArrayRef[Molecule::Atom]', required => 1, weak_ref => 1, default => sub { [] }, ); sub add_verlet{ my $self = shift; print $self->{id},"\n"; my $array = $self->{verlet}; foreach my $obj (@_){ print "adding :", $obj->{id},"\n"; push(@{$array},$obj); weaken(@{$array}[-1]); } print "Array dim = $#{$array}\n"; } sub print_verlet{ my $self = shift; my $array = $self->{verlet}; print "Verlet from Atom ", $self->{id}, "\n"; foreach my $obj (@{$array}){ print "Verlet list :", $obj->{id},"---->\n"; } }
in the main program:
$atom1a = Molecule::Atom->new(O); $atom1b = Molecule::Atom->new(X); $atom1c = Molecule::Atom->new(Y); $atom2a = Molecule::Atom->new(Z); $atom1a->add_verlet($atom1c,$atom1b); $atom1a->add_verlet($atom2a); $atom1a->print_verlet();
output:
8 adding :10 adding :9 Array dim = 1 8 adding :11 Array dim = 0 Verlet from Atom 8
What it should be:
8 adding :10 adding :9 Array dim = 1 8 adding :11 Array dim = 2 Verlet from Atom 8 Verlet list 10 Verlet list 9 Verlet list 11
What I am doing wrong?
I am starting to program in Moose, so the meaning of certain issues with Moose I don not fully understand. As far I know, this code should work. I also try:
has 'verlet' => ( traits => ['Array'], is =>'rw', isa => 'ArrayRef[Molecule::Atom]', required => 1, weak_ref => 1, default => sub { [] }, handles => { add_atom =>'add_verlet', } );
But I get compilation error like: I can not find add_atom in the package. So, definitively there is something I am doing wrong.
Is there anyone understand my problem?
Playing a bit found that "weak_ref => 0" works!!! If I do not understand bad, I need weak_ref => 1 because I do not want destroying the objects stored in the vector, so I see that the actual question is how I said to perl that I do not want to destroy the objects stored in the array?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Moose and arrays of objects
by moritz (Cardinal) on Dec 03, 2012 at 10:37 UTC |