[Wellington-pm] Creating an array of objects

Cliff Pratt enkidu at cliffp.com
Sat Mar 11 14:06:52 PST 2006


Jacinta Richardson wrote:
> Cliff Pratt wrote:
> 
> 
>>I basically want to create an array of objects or object refs, so can I do :
>>
>>my @foo;
>>$foo[0] = MyPackage->new('tut') ;
>>$foo[1] = MyPackage->new('ankh') ;
>>$foo[2] = MyPackage->new('amun') ;
>>
>>Obviously this could be done using a loop, but what if I needed an array
>>of a hundred of them? Is there a clever way to instantiate a hundred
>>objects of a particular class?
> 
> 
> my @foo;
> foreach my $name (qw/tut ankh amun/) {
> 	push @foo, MyPackage->new($name);
> }
> 
> 
> or
> 
> my @setup = (
> 	{
> 		name => "tut",
> 		... => ...,
> 	},
> 	{
> 		name => "ankh",
> 		... => ...,
> 	},
> 	{
> 		name => "amun",
> 		... => ...,
> 	},
> );  # data probably generated in some useful form elsewhere.
> 
> my @foo;
> foreach my $details (@setup) {
> 	push @foo, MyPackage->new(%$details);  # assuming named parameters
> }
> 
> 
> If you need an array of 100, or 50, or even 4, this is as good a method as any.
> 
Thanks all, this is for a gameboard situation where the array, is the 
array of cells on the gameboard. Like a calculator app has lots of 
button objects, the gameboard has a lot of cell objects which I plan to 
hold references to in an array. Grant says that the constructor returns 
a reference, and that makes it easier.

I might just build the array on the fly, when needed.

Thanks again everyone. I'm off to read 'perltoot' again to see if it now 
makes more sense to me!

Cheers,

Cliff

-- 

http://barzoomian.blogspot.com


More information about the Wellington-pm mailing list