Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using localtime inside moose default values

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 ?

like image 847
mbonnin Avatar asked Jan 16 '12 17:01

mbonnin


1 Answers

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"}} });
like image 112
daxim Avatar answered Sep 28 '22 14:09

daxim