Coerce is used to convert a different type of the value, while isa is used to just check the type is correct. You can define both of them, in such a case isa is run after coerce, i.e. it checks whether the coercion worked correctly.
#! /usr/bin/perl use warnings; use strict; use Time::Piece; { package My; use Moo; use Time::Piece; sub is_date { my ($date) = @_; die "Wrong type" unless shift->isa('Time::Piece'); } use namespace::clean; has time_piece => (is => 'rw', isa => \&is_date); has string_date => ( is => 'rw', coerce => sub { my $tp = shift; $tp = 'Time::Piece'->strptime($tp, '%Y%m%d') unless $tp->isa('Time::Piece'); return $tp }, isa => \&is_date); } my $now = localtime; my $o = 'My'->new( time_piece => $now, string_date => '20170911' ); eval { $o->string_date($now) } or warn "1: $@"; # works eval { $o->string_date('a') } or warn "2: $@"; # coercion for "s +tring_date" failed: Error parsing time eval { $o->time_piece('20170911') } or warn "3: $@"; # isa check for " +time_piece" failed: Wrong type
($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

In reply to Re: Moo's coerce and isa difference by choroba
in thread Moo's coerce and isa difference by krautcat

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.