note
tobyink
<p>As per [kennethk]'s suggestion, something like:</p>
<code>
my @users = map { User->new($_) } @user_ids;
</code>
<p>... 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.</p>
<code>
{
package User;
...;
sub multi_new {
my $class = shift;
return map { $class->new($_) } @_;
}
}
my @users = User->multi_new(@user_ids);
</code>
<p>I wouldn't do it directly in <c>new</c>. While <c>new</c> 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.</p>
<p>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 <c>multi_new</c> to construct multiple instances of your class without worrying about what happens inside <c>multi_new</c>. Perhaps in the future you'll discover a new, more efficient implementation for <c>multi_new</c>; you can change the internals and people using your class will get the more efficient behaviour for free.</p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-757127">
<small><small>
<tt>perl -E'sub Monkey::do{say$_,for@_,do{($monkey=&#x5B;caller(0)]->&#x5B;3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
</tt></small></small>
</div></div>
1003841
1003841