learning.moose has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks, how I can add default values to a hash like that?

has 'url' => ( is => 'rw', isa => 'HashRef', default => sub {}, );

I want my hash to have some default values, like:

$url = { 'url1' => 'perlmonks.org'}

Replies are listed 'Best First'.
Re: Moose hash with default values
by kcott (Archbishop) on Jun 04, 2015 at 20:09 UTC

    G'day learning.moose,

    default => sub { { 'url1' => 'perlmonks.org'} }

    It's documented in Moose. Look for has and its subsection default.

    "... if you wish to initialize it with a HASH or ARRAY ref, then you need to wrap that inside a CODE reference."

    If you really are learning Moose then you should read all of that (fairly short) document. It provides basic information with links to more detailed information and advanced topics.

    -- Ken

Re: Moose hash with default values
by GotToBTru (Prior) on Jun 04, 2015 at 20:16 UTC

    Moose::Manual::Attributes says: "If you want to use a reference of any sort as the default value, you must return it from a subroutine. has 'mapping' => ( is => 'ro', default => sub { {} }, );

    So perhaps:

    has 'url' => (is => 'rw', isa => 'HashRef', default => sub{ {'url1' => + 'perlmonks.org'}}, );

    I can't test; I've never used Moose.

    Dum Spiro Spero
Re: Moose hash with default values
by GotToBTru (Prior) on Jun 04, 2015 at 19:58 UTC

    This isn't covered in Moose 101?

    Dum Spiro Spero
      Whats Moose 101?

        Any one of the Moose tutorials out on the web.

        Dum Spiro Spero

      This isn't covered in Moose 101? ...

      Do you know where it is covered GotToBTru?