tags:

views:

111

answers:

1

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?

+9  A: 

The anonymous array reference constructor is [] not () which is used to group statements into lists. The () in this case flattens to an empty list and perl sees my $self = { item => };. If you were running with use warnings; you would have gotten a message about that.

Also, in your get subroutine you will probably want to dereference your field to return the list instead of a reference to the array:

sub get {
    return @{ $_[0]->{items} };
}
Eric Strom
Thanks! Everything works fine now
Laimoncijus