以下代码有什么问题?运行时,我得到:“在连接(。)中使用未初始化的值或在./main.pl第14行使用字符串”
#!/usr/bin/perl
package Test;
use Moose;
has 'message' => (isa => 'HashRef', is => 'ro', default => sub{{(localtime)[2] => {(localtime)[3] => "hello"}}});
# the one below works fine
#has 'message' => (isa => 'HashRef', is => 'ro', default => sub{{"18" => {"16" => "hello"}}});
sub show {
my $self = shift;
print("Test: " . $self->message->{(localtime)[2]}->{(localtime)[3]} . "\n");
}
my $o = Test->new();
$o->show();
如果我不使用localtime()那么它工作正常。本地时间[2]和[3]也不会经常变化(2是小时,3是月份日)所以问题不是这样。如果我使用调试器运行脚本,我会得到:
x $self
0 Test=HASH(0x3597300)
'message' => HASH(0x3597618)
16 => 'hello'
所以看起来我'失去'一级间接,不确定为什么......任何想法?
答案 0 :(得分:10)
外部{}
不会解析为hashref。添加明确的return
:
has 'message' => (isa => 'HashRef', is => 'ro', default => sub{ return {(localtime)[2] => {(localtime)[3] => "hello"}} });
+
强制推行此功能。
has 'message' => (isa => 'HashRef', is => 'ro', default => sub{ +{(localtime)[2] => {(localtime)[3] => "hello"}} });