gpt4 book ai didi

perl - 在 moose 默认值中使用 localtime

转载 作者:行者123 更新时间:2023-12-04 14:04:37 25 4
gpt4 key购买 nike

下面的代码有什么问题?运行时,我得到:“在 ./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() 那么它工作正常。 localtime[2] 和 [3] 也不会经常改变(2 是小时,3 是月日)所以问题不是那个。如果我使用调试器运行脚本,我会得到:
x $self
0 Test=HASH(0x3597300)
'message' => HASH(0x3597618)
16 => 'hello'

所以看起来我“失去”了一层间接,不确定为什么......知道吗?

最佳答案

{}不要解析为 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"}} });

关于perl - 在 moose 默认值中使用 localtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8883855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com