It took me a little while to figure this one out so I thought I post it here, partly to make it easier for myself to find it next time ;-)

I write software for biological applications and I use Moose. My modules often take biological sequence data as input, so I create a subtype for strings that fulfill a regex for valid DNA sequences (in this case I only allow the letters A,G,T, C and N). This is in a package MyApp::MooseX::MyTypes:

subtype 'DNAString' => as Str => where { $_ && $_=~/^[AGCTN]+$/i} => message {"Not a DNA string: only AGCT or N allowed and cannot be +empty"};
Now my modules can define attributes like this:
use MyApp::MooseX::MyTypes: has sequence => ( isa => 'DNAString', );
So far so good, but sequences in biological applications in Perl often exist in the form of Bio::Seq objects and I thought it would be nice if my DNAString type could automatically get the sequence string from such objects. However, you can only coerce from Moose built-in types, so I wanted to say: coerce from an incoming object into a sequence string, if that object has a 'seq' method (which returns the sequence as a string in BioPerl).
Turns out that this can be done like this (in MyApp::MooseX::MyTypes again):
coerce 'DNAString' => from duck_type( ['seq'] ) => via { $_->seq };
And then you need to tell the constructor that you want to use coercions for this attribute by adding the 'coerce' switch:
use MyApp::MooseX::MyTypes: has sequence => ( isa => 'DNAString', coerce => 1, );
Now all my modules that used to only accept sequence strings, automatically except Bio::Seq objects as well.

In reply to Of moose and ducks (or: how to coerce from non-Moose type objects) by tospo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.