Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define an empty array in a Perl construtor?

Tags:

arrays

oop

perl

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?

like image 763
Laimoncijus Avatar asked Dec 29 '22 18:12

Laimoncijus


1 Answers

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} };
}
like image 198
Eric Strom Avatar answered Jan 19 '23 06:01

Eric Strom