2012-01-16 48 views
6

下面的代碼有什麼問題?當運行時,我得到:「未初始化值的串聯或串用在./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' 

所以它看起來像我「丟失」一個間接層,真的不知道爲什麼......你知道嗎?

回答

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"}} }); 
+0

工作正常,謝謝 – mbonnin 2012-01-17 09:39:54

+0

只是爲了我的理解:在這種情況下,外部{}解析是什麼?它被忽略了嗎? – mbonnin 2012-01-17 09:41:23

+0

好的,理解,這個問題可以解答:http://stackoverflow.com/questions/1617546/whats-the-history-of-the-in-front-of-a-hashref-that-disambiguates-from-a-代碼 再次感謝。 – mbonnin 2012-01-17 09:44:09