在驼鹿默认值中使用当地时间

发布于 2024-12-27 13:04:09 字数 849 浏览 0 评论 0原文

下面的代码有什么问题?运行时,我得到:“在连接 (.) 或 ./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'

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

What's wrong with the code below ? When run, I get: "Use of uninitialized value in concatenation (.) or string at ./main.pl line 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();

If I do not use localtime() then it works fine. Also localtime[2] and [3] do not change very often (2 is hours, 3 is month day) so the problem is not that. If I run the script with a debugger, I get:

x $self
0  Test=HASH(0x3597300)
   'message' => HASH(0x3597618)
      16 => 'hello'

So it looks like I 'lose' one level of indirection, not really sure why... Any idea ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜巴黎 2025-01-03 13:04:09

外部 {} 不会解析为哈希引用。添加显式的 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"}} });

The outer {} do not parse as a hashref. Add an explicit return:

has 'message'     => (isa => 'HashRef', is => 'ro', default => sub{ return {(localtime)[2] => {(localtime)[3] => "hello"}} });

A + to force this works, too.

has 'message'     => (isa => 'HashRef', is => 'ro', default => sub{ +{(localtime)[2] => {(localtime)[3] => "hello"}} });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文