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...)
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;
You can say
@objects = (new MyPackage::MyObject(), new MyPackage::MyObject(), new MyPackage::MyObject());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With