[Wellington-pm] Creating an array of objects

Jacinta Richardson jarich at perltraining.com.au
Sat Mar 11 12:07:09 PST 2006


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.

    Jacinta

-- 
   ("`-''-/").___..--''"`-._          |  Jacinta Richardson         |
    `6_ 6  )   `-.  (     ).`-.__.`)  |  Perl Training Australia    |
    (_Y_.)'  ._   )  `._ `. ``-..-'   |      +61 3 9354 6001        |
  _..`--'_..-_/  /--'_.' ,'           | contact at perltraining.com.au |
 (il),-''  (li),'  ((!.-'             |   www.perltraining.com.au   |




More information about the Wellington-pm mailing list