开发者

Perl: Constructing an array of objects

开发者 https://www.devze.com 2023-04-07 10:13 出处:网络
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.

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 MyP开发者_如何学Pythonackage::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 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(),
);


You can say

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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消