Jeremy Jeremy - 5 months ago 11
Perl Question

Perl -- unable to construct array of objects

I've tried two similar bits of syntax. This first one works:

my $obj = PI::something::ObjectManipulator->new();
$obj->setValue('HELLO');
my $objList = [$object];


This, however, doesn't:

my $objList= [];
foreach my $value (@values) {
my $obj = PI::something::ObjectManipulator->new();
$obj->setValue($value);
push @$objList, $obj;
};


What is the difference between these two way of doing things? Why doesn't the second work? (By not work, it seems to be that $objList is still empty at the end of the code.)

Answer

Assuming my $objList = [$object]; is a typo for my $objList = [$obj];, and assuming, my @values = 'HELLO';, there are no differences.

Assuming you meant "@$objList is still empty" when you said "$objList is still empty", that can only happen if the loop isn't entered (i.e. @values is empty).

Comments