using localtime inside moose default values
Asked Answered
C

1

6

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 ?

Continual answered 16/1, 2012 at 17:28 Comment(0)
Z
10

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"}} });
Zambrano answered 16/1, 2012 at 18:1 Comment(2)
Just for my understanding: what does the outer {} parse as in this case ? Is it just ignored ?Continual
Ok, understood, this question answers it: #1618046 Thanks again.Continual

© 2022 - 2024 — McMap. All rights reserved.