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 ?
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"}} });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With