perl - Dynamical array as a class member -
there following class:
package myclass; use strict; use warnings; sub new { $class = shift(); $self = { _class_array => [] }; bless ($self, $class); return $self; }
how can set/get add values array?
i tried following code:
sub adddatatype { $self = shift(); $new_element = shift(); @array = $self->{_class_array}; print("number of elements ".($self->{_class_array})."\n"); push(@array, $new_element); $self->{_class_array} = @array; print("element added. number of elements ".($self->{_class_array})."\n"); }
the output following:
number of elements array(0x21bb4c)
element added. number of types 2
number of elements 2
element added. number of types 2
number of elements 2
element added. number of types 2
questions are:
- what mean:
number of elements array(0x21bb4c)
? - why array length stays
2
?
you using arrayref array. try:
sub adddatatype { ( $self, $new_element ) = @_; print "number of elements " . scalar @{ $self->{_class_array} } . "\n"; push @{ $self->{_class_array} }, $new_element; print "element added. number of elements " . scalar @{ $self->{_class_array} } . "\n"; return; }
Comments
Post a Comment