使用 perl Moo 在 new() 方法中使用子例程
using a subroutine in the new() method using perl Moo
我的问题是:我想在使用perl Moo调用new()方法创建对象时使用子程序构造数组。请看下面的例子。
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;
基本上,我正在尝试从数据库中检索一些电子邮件,不要担心查询和数据库访问,因为当我执行以下操作时:
my $cc= Customer->new(id=>92,type=>'xxxxxxx');
@emails=$cc->getEmails();
@emails 中的结果符合预期。但是,当我执行时:
my $cc= Customer->new(id=>92,type=>'xxxxxxx');
@emails=$cc->emails;
我什至没有结果。
如果我能得到这个问题的答案,我将不胜感激。提前谢谢大家。
您想使用构建器方法或默认方法,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
参数添加到您的电子邮件属性。这只会在它调用时初始化它。
我的问题是:我想在使用perl Moo调用new()方法创建对象时使用子程序构造数组。请看下面的例子。
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;
基本上,我正在尝试从数据库中检索一些电子邮件,不要担心查询和数据库访问,因为当我执行以下操作时:
my $cc= Customer->new(id=>92,type=>'xxxxxxx');
@emails=$cc->getEmails();
@emails 中的结果符合预期。但是,当我执行时:
my $cc= Customer->new(id=>92,type=>'xxxxxxx');
@emails=$cc->emails;
我什至没有结果。
如果我能得到这个问题的答案,我将不胜感激。提前谢谢大家。
您想使用构建器方法或默认方法,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
参数添加到您的电子邮件属性。这只会在它调用时初始化它。