[Wellington-pm] Creating an array of objects
grant at mclean.net.nz
Sat Mar 11 02:02:39 PST 2006
On Sat, 2006-03-11 at 21:58 +1300, Cliff Pratt wrote:
> I can, I believe, instantiate an object as follows (please correct me if
> I'm wrong)
> my $foo = MyPackage->new('bar') ;
> Is $foo an object or an object reference?
Strictly speaking, it is a reference to an object, but the distinction
is seldom important. For all intents and purposes, $foo is an object.
You can call methods on it and Perl can locate those methods via the
package name that was associated with the reference using 'bless'.
> I basically want to create an array of objects or object refs, so can I do :
> my @foo;
> $foo = MyPackage->new('tut') ;
> $foo = MyPackage->new('ankh') ;
> $foo = 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?
Using a loop might be a perfectly reasonable way to create lots of
objects. There are other possibilities.
For example, Class::DBI provides an object wrapper around relational
database entities. For example, you might use it to create a 'Product'
class that maps to the 'product' table in your database. Then you might
use the search method from that class to create an array of Product
objects representing rows from the product table which met some
my @red_prods = Product->search(colour => 'red');
Under the covers, a SQL query will be constructed and executed. Then a
loop will be used to iterate through the query result set and create an
object for each row.
> Am I making sense? The experienced OO programmers are probably laughing
> themselves silly by now....
You seem to be making sense, but may be trying to think about things in
too abstract a way. Bring it back to something more concrete by looking
at what would be the unique identifying features of each object you
create. Where would the data come from?
More information about the Wellington-pm