Folks,
I am having a problem which I have so far failed to solve myself mainly, I suspect, because I don't understand the problem well enough!
I have a package with an object TESTOBJ which includes a name and, as one of the elements, an array (__mpp). When I use this object I want to be able to store up to ten values in __mpp.
In my application I am trying to build an array of TESTOBJ using the constructor to create each object. The problem is that I seem only to have one array (__mpp) shared between all my objects!
In the sample code below I create two TESTOBJ and populate them but when I set __mpp in the second object it affects __mpp in the first. Why is this ?
use TESTOBJ; my @res = (); my $t = new TESTOBJ; $t->name("first"); $t->mpp0(111); $res[0] = $t; printf "Dump \$res[0]: name '%s' mpp '%d'\n", $res[0]->name(), $res[0]->mpp0(); $t = new TESTOBJ; $t->name("second"); $t->mpp0(222); $res[1] = $t; printf "Dump \$res[0]: name '%s' mpp '%d'\n", $res[0]->name(), $res[0]->mpp0(); printf "Dump \$res[1]: name '%s' mpp '%d'\n", $res[1]->name(), $res[1]->mpp0();
And TESTOBJ.pm contains
package TESTOBJ; my %fields = ( __name => undef, __mpp => [ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ] ); sub new { my $that = shift; my $class = ref($that) || $that; my $self = { %fields }; bless $self, $class; return $self; } sub name { my $obj = shift; @_ ? $obj->{__name} = shift # modify attribute : $obj->{__name}; # retrieve attribute } sub mpp0 { my $obj = shift; @_ ? $obj->{__mpp}[0] = shift # modify attribute : $obj->{__mpp}[0]; # retrieve attribute }
Regards, Gavin
In reply to Anonymous array in object by GGGav
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |