Hi Moosers,

I am quite new to Moose, at least I don't use all the power of it.
Anyway, I tried to create a subtype called 'ArrayRefOrHashRef' to be
able to have an attribute that could accept and array ref or a hash
ref. My idea is to :

1) If the parameter passed to my attribute is an array ref, work
with it and then create a hash ref at the end
2) It the parameter passed to my attribute is a hash ref, check some
stuff then return it modified or not.

Here is my code :

 subtype 'ArrayRefOrHashRef'
  => as 'Ref'
  => where { ref($_) eq 'ARRAY' or ref($_) eq 'HASH' };

coerce 'ArrayRefOrHashRef'
  => from 'ArrayRef'
  => via {
      my $hash = { };

      foreach my $type (@{$_}){
          throw Bio::Root::BadParameter(
              "Wrong type value '$type' [cohesive|blunt]!")
            unless($type =~ /^[cohesive|blunt]$/o);
          $hash->{$type} = $type eq 'cohesive' ? [qw/5' 3'/] :
[qw/blunt/];
      }
      return $_ = $hash;
   }
  => from 'HashRef'
  => via {
     #do some stuff with hash ref.
  };

later on:

has 'cut_types' => (
    is        => 'ro',
    isa       => 'ArrayRefOrHashRef',
    coerce    => 1,
    required  => 1,
    default   => sub { {'cohesive' => [qw/5' 3'/], 'blunt' =>
[qw/blunt/]} },
);

However,if I passed an array ref to 'cut_types'
it does not get transform to a hash ref.

my $t = Object->new(-cut_types => ['foo']);
#then $t->cut_types() returns an array ref :(

So can somebody tell me what I am doing wrong?
Also, is there a way to get some value or text printed from inside
the coercion code ?

Thanks in advance

Regards

Emmanuel

-- 
-------------------------
Emmanuel Quevillon
Biological Software and Databases Group
Institut Pasteur
+33 1 44 38 95 98
tuco at_ pasteur dot fr
-------------------------

Reply via email to