下面的代码有什么问题?运行时,我得到:“在连接(.)中使用未初始化的值或在./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',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'
所以看起来我’失去’一级间接,不确定为什么……任何想法?
解决方法
外部{}不会解析为hashref.添加显式返回:
- has 'message' => (isa => 'HashRef',default => sub{ return {(localtime)[2] => {(localtime)[3] => "hello"}} });
一个强制这个也有效.
- has 'message' => (isa => 'HashRef',default => sub{ +{(localtime)[2] => {(localtime)[3] => "hello"}} });