6

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...)

0

4 Answers 4

9

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I just love that first answer, would never have thought of that.
I voted up the answer, because I would use map too, but boo on the indirect object syntax MyPackage::MyObject0->new() is much much much better, the other way brings many ambiguities.
In fact, they are talking about removing indirect object syntax in a future version readwriteweb.com/hack/2011/09/… frame 271. Also see perldoc perlobj
The first solution is pure beauty, and exactly what I hoped to find. @Joel Berger: Thanks for the hint, I'd never have thought that the so familiar-looking new ... syntax had footholes in Perl.
2

You can avoid the loop and repeating the same statement by supplying multiple arguments to push:

push(@objects, 
  new MyPackage::MyObject(), 
  new MyPackage::MyObject(), 
  new MyPackage::MyObject());

This is possible because the prototype of push is push ARRAY,LIST.

Or you can do it in a more straightforward way with an array composer (preferable):

my @objects = (
  new MyPackage::MyObject(), 
  new MyPackage::MyObject(), 
  new MyPackage::MyObject(),
);

Comments

1

You can say

@objects = (new MyPackage::MyObject(), new MyPackage::MyObject(), new MyPackage::MyObject());   

Comments

0

You can construct a list of objects and assign it to your array:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.