How can I define an empty array in Perl construtor?

I'm just starting out with Perl, so if that sounds stupid - sorry for that :)

My problem is I am trying to write a class that has an empty array defined in the class constructor. Therefore, I do it as follows:

package MyClass; use strict; sub new { my ($C) = @_; my $self = { items => () }; bless $self, ref $C || $C; } sub get { return $_[0]->{items}; } 1; 

Later I test my class with a 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 when I run the script, I get the following:

 $ perl my_test.pl length = 1 $VAR1 = undef; 

Why am I doing wrong that causes me to get an items array filled with undef ?

Can someone show me an example of how a class should be defined so that I don't get any default values โ€‹โ€‹in my array?

+4
source share
1 answer

The link constructor of the anonymous array [] not () , which is used to group statements into lists. () in this case is aligned to an empty list, and perl sees my $self = { item => }; . If you work with use warnings; , you would receive a message about this.

Also, in your get routine, you probably want to dereference your field to return a list instead of an array reference:

 sub get { return @{ $_[0]->{items} }; } 
+10
source

Source: https://habr.com/ru/post/1307901/


All Articles