Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Constructing an array of objects

Tags:

oop

perl

swig

Partially related to this question but different, as this is about constructor calls...

I would like to create an array of a fixed number of objects.

I could do this:

my @objects;
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
push( @objects, new MyPackage::MyObject() );
# ...

That's several kinds of ugly. Making it a loop is only marginally better.

Isn't there a way to create an array of (constructor-initialized) objects in Perl?

Afterthought question:

These "objects" I want to create are actually SWIG-generated wrappers for C structs, i.e. data structures without "behaviour" (other than the SWIG-generated get and set functions). I just want to pass the array as a parameter to the C function, which will fill the structures for me; do I need to call constructors at all, or is there a shortcut to having the get functions for reading the struct contents afterwards? (Yes, I am awfully new to OOPerl...)

like image 649
DevSolar Avatar asked Sep 26 '11 15:09

DevSolar


2 Answers

There Is More Than One Concise Way To Do It:

my @objects = map { new MyPackage::MyObject() } 1..$N;

my @objects = ();
push @objects, new MyPackage::MyObject() for 1..$N;
like image 137
mob Avatar answered Oct 15 '22 13:10

mob


You can say

@objects = (new MyPackage::MyObject(), new MyPackage::MyObject(), new MyPackage::MyObject());   
like image 31
Jonathan M Avatar answered Oct 15 '22 14:10

Jonathan M