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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.