http://www.perlmonks.org?node_id=1003847


in reply to OOP: How to construct multiple instances of a class at once

As per kennethk's suggestion, something like:

my @users = map { User->new($_) } @user_ids;

... is the best way to do this. However, if you find yourself doing that frequently, then you could bundle that functionality up into a class method in the User package.

{ package User; ...; sub multi_new { my $class = shift; return map { $class->new($_) } @_; } } my @users = User->multi_new(@user_ids);

I wouldn't do it directly in new. While new is just a sub and you can technically do whatever you like with it, there is a strong convention that it should return a single instance of the class. Having it potentially return multiple instances will surprise users of your module... and not in a good way.

Bundling it up into a class method gives you the opportunity to take advantage of "encapsulation" at a later date. People using your class will be calling multi_new to construct multiple instances of your class without worrying about what happens inside multi_new. Perhaps in the future you'll discover a new, more efficient implementation for multi_new; you can change the internals and people using your class will get the more efficient behaviour for free.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'