|
|
| Pathologically Eclectic Rubbish Lister | |
| PerlMonks |
Re: OOP: How to construct multiple instances of a class at onceby tobyink (Prior) |
| on Nov 14, 2012 at 16:12 UTC ( #1003847=note: print w/ replies, xml ) | Need Help?? |
|
As per kennethk's suggestion, something like:
... 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.
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'
In Section
Seekers of Perl Wisdom
|
|
||||||||||||||||||||