1

我的问题如下:当我调用 new() 方法使用 perl Moo 创建一个对象时,我想使用一个子例程来构造一个数组。请看下面的例子。

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;

我什至没有结果。

如果我能得到这个问题的答案,我将不胜感激。提前谢谢各位。

4

1 回答 1

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参数添加到您的电子邮件属性。这只会在它调用时初始化它。

于 2016-04-15T20:39:07.890 回答