Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to generate a Moose hash with the keys and values generated by passing in a string such as:

foo=bar,foo2=bar2,foo3=bar3

etc.. and then being able to access the value via $self->myhash('foo');

I've tried coerce on a subtype with via => performing the 2 splits required.. I'm missing something.. I can't get this to work no matter what I try.

Can someone point me in the right direction?

Replies are listed 'Best First'.
Re: Moose coerce
by ikegami (Patriarch) on Oct 20, 2010 at 17:04 UTC

    Please provide a minimal demonstration of the problem. At the very least, tell us how it's failing.

    • Did you specify coerce=>1 on the attribute?

    • Is your coercion routine getting called?

    • Is your coercion routine return a reference to a hash as it should (as opposed to a list of key-values)?

    • What is your coercion routine returning, exactly? Change

      return ...;

      to

      my @x = ...; use Data::Dumper; warn(Dumper(\@x)); return $x[0];
      Thanks for your reply - I've posted the code above..
Re: Moose coerce
by zwon (Abbot) on Oct 20, 2010 at 16:52 UTC
    I've tried coerce on a subtype with via => performing the 2 splits required.. I'm missing something.. I can't get this to work no matter what I try.

    Could you post the code you tried?

      Here's the code I'm working with (comments inline):
      package test; use Moose; use Moose::Util::TypeConstraints; subtype 'mytype' => as 'HashRef[Str]' ; coerce 'mytype' => from 'Str' => via { my %h = map { split('=', $_) } split(',', $_); return \%h; } ; has 'mytype' => ( traits => ['Hash'], is => 'rw', isa => 'mytype', coerce => 1, # presumably I need an explicit accessor # to prevent coercion when I pass # a key in to access the value? handles => { get_option => 'get', }, ); package main; use Data::Dumper; my $t = test->new; # coerce into a hash $t->mytype('foo=bar,foo2=bar2'); warn Dumper $t->mytype; # how do i now access the hash by key? # this tries to coerce all over again! warn $t->mytype('foo'); # and this doesn't work at all warn $t->mytype_get('foo');

        Your module works fine:

        # ... all same above ... package main; use Data::Dumper; my $t = test->new; $t->mytype('foo=bar,foo2=bar2'); warn Dumper $t->mytype; # Don't call $t->mtype('foo') # Use correct method name!! warn $t->get_option('foo');

        Good Day,
            Dean