perl – 在moose默认值中使用localtime

前端之家收集整理的这篇文章主要介绍了perl – 在moose默认值中使用localtime前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
下面的代码有什么问题?运行时,我得到:“在连接(.)中使用未初始化的值或在./main.pl第14行使用字符串”
  1. #!/usr/bin/perl
  2.  
  3. package Test;
  4.  
  5. use Moose;
  6.  
  7. has 'message' => (isa => 'HashRef',is => 'ro',default => sub{{(localtime)[2] => {(localtime)[3] => "hello"}}});
  8.  
  9. # the one below works fine
  10. #has 'message' => (isa => 'HashRef',default => sub{{"18" => {"16" => "hello"}}});
  11.  
  12. sub show {
  13. my $self = shift;
  14. print("Test: " . $self->message->{(localtime)[2]}->{(localtime)[3]} . "\n");
  15. }
  16.  
  17. my $o = Test->new();
  18. $o->show();

如果我不使用localtime()那么它工作正常.本地时间[2]和[3]也不会经常变化(2小时,3是月日)所以问题不是那样.如果我用调试器运行脚本,我得到:

  1. x $self
  2. 0 Test=HASH(0x3597300)
  3. 'message' => HASH(0x3597618)
  4. 16 => 'hello'

所以看起来我’失去’一级间接,不确定为什么……任何想法?

解决方法

外部{}不会解析为hashref.添加显式返回:
  1. has 'message' => (isa => 'HashRef',default => sub{ return {(localtime)[2] => {(localtime)[3] => "hello"}} });

一个强制这个也有效.

  1. has 'message' => (isa => 'HashRef',default => sub{ +{(localtime)[2] => {(localtime)[3] => "hello"}} });

猜你在找的Perl相关文章