daveman has asked for the wisdom of the Perl Monks concerning the following question:

How do you add an element on to an array within a class. I have the following class

package MyClass;

   my @fields;

sub new
{
   my $this = {};
   $this->{fields}=undef;
    bless $this;
    return $this;
}

sub addValue
{
    push $this->{fields}, "some value";
}

I know this is the incorrect syntax because I am getting an error. Can you use the oush method to add an element? If not, what is the best way to do this?

Replies are listed 'Best First'.
Re: How do you add class array values
by tomhukins (Curate) on Apr 12, 2001 at 22:23 UTC

    Others have already answered your question, but nobody has mentioned that you don't need to use my @fields; in the third line of your code.

    Your new method creates an array ref ($this) which contains a value whose key is fields. This hash element is independent of any other data structure in your code - it isn't connected to the @fields you have already declared.

Re: How do you add class array values
by suaveant (Parson) on Apr 12, 2001 at 22:12 UTC
    Your push $this->{fields}, "some value"; is not right, either... you'll need to do
    push @{$this->{fields}}, "some value";
    so the hash value will be treated as an array...

    oh, and packages must end in a true value, so many people put a 1; as the last line of their package
                    - Ant

A reply falls below the community's threshold of quality. You may see it by logging in.