Using localtime inside moose defaults

What happened to the code below? When I start, I get: "Using an uninitialized value in concatenation (.) Or a string in a string. /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(); 

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

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

So it looks like I'm β€œlosing” one level of indirection, not quite sure why ... Any idea?

+6
source share
1 answer

External {} not parsed as hashref. Add an explicit return :

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

A + to make this work too.

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

Source: https://habr.com/ru/post/906136/


All Articles