Define an empty array in Perl class new()
Posted
by Laimoncijus
on Stack Overflow
See other posts from Stack Overflow
or by Laimoncijus
Published on 2010-04-24T23:32:10Z
Indexed on
2010/04/24
23:43 UTC
Read the original article
Hit count: 240
Hi,
I am just beginner with Perl, so if it sounds stupid - sorry for that :)
My problem is - I am trying to write a class, which has an empty array, defined in constructor of a class. So I am doing this like this:
package MyClass;
use strict;
sub new {
my ($C) = @_;
my $self = {
items => ()
};
bless $self, ref $C || $C;
}
sub get {
return $_[0]->{items};
}
1;
Later I am testing my class with simple script:
use strict;
use Data::Dumper;
use MyClass;
my $o = MyClass->new();
my @items = $o->get();
print "length = ", scalar(@items), "\n", Dumper(@items);
And while running the script I get following:
$ perl my_test.pl
length = 1
$VAR1 = undef;
Why am I doing wrong what causes that I get my items
array filled with undef
?
Maybe someone could show me example how the class would need to be defined so I would not get any default values in my array?
Thanks!
© Stack Overflow or respective owner