我的问题如下:当我调用new()方法使用perl Moo创建对象时,我想使用子例程来构造数组。请参阅以下示例。
NSString
基本上,我正在尝试从数据库中检索一些电子邮件,并且不用担心查询和数据库访问,因为当我执行以下操作时:
NSPathStore2
@emails的结果是预期的。但是,当我执行:
package Customer;
use DBI;
use 5.010;
use Data::Dumper;
use Moo;
use FindBin qw/$Bin/;
use lib "$Bin/../../../lib";
use lib '/home/fm/lib';
use TT::SQL;
has id => (
is=>'ro',
required=>1,
);
has type => (
is=>'ro',
);
has emails => (
is=>'rw',
isa => sub {getEmails() },
);
sub getEmails
{
#connecting into de DB
my $self=shift;
my $db2 = TT::SQL::get_handler("xxxxxx","xxxxx");
my $fmuser=$self->id;
my $type=$self->type;
my $query;
#checking the customer type to perform the query
if ($type eq "xxxxxxxxxx")
{
$query=xxxxxxxxxxxxxx;
}
else
{
$query=xxxxxxxxxxxxxx;
}
my $ref = $db2->execute($query,$fmuser);
my @emails;
#retrieving emails
while ( my $row = $ref->fetchrow_hashref ) {
@emails=(@emails,"$row->{email}\n");
}
return @emails;
}
1;
我甚至没有结果。
如果我得到这个问题的答案,我将非常感激。先谢谢你们。
答案 0 :(得分:4)
您想要使用构建器方法或默认值,isa用于强制执行类型约束:
默认:
has emails => (
is => 'rw',
default => sub {
my ($self) = @_;
return $self->getEmails();
},
);
助洗剂:
has emails => (
is => 'rw',
builder => '_build_emails',
);
sub build_emails {
my ($self) = @_;
return $self->getEmails();
}
如果getEmails()
子例程需要任何额外的启动时间(例如获取数据库句柄),我还建议将lazy => 1
参数添加到您的电子邮件属性中。这只会在调用时初始化它。