Type::Tiny Tricks #3: One-off Coercions

Here's a quick way to create an attribute that coerces to an integer from any other number:

   package Local::Eg3;
   use Moose;
   use Types::Standard -types;
   
   has foo => (
      is      => "ro",
      isa     => Int->plus_coercions( Num, sub{int($_)} ),
      coerce  => 1,
   );
   
   __PACKAGE__->meta->make_immutable;

You can express the coercion as a string of Perl code, which will in some circumstances help Type::Tiny optimize things.

   has foo => (
      is      => "ro",
      isa     => Int->plus_coercions( Num, 'int($_)' ),
      coerce  => 1,
   );

Caveats

Don't forget the coerce => 1 bit. It's very easy to forget.

If you're supplying multiple coercions, it might seem clearer to use a fat comma:

   Int->plus_coercions(
      Num       => sub { int($_) },
      ArrayRef  => sub { scalar(@$_) },
      Undef     => sub { 0 },
   )

This will not work because of the auto-quoting powers of =>. Take a look at the winking fat comma in perlsecret though.

1 Comment

As of Moo v1.006000 this will work too as it just added coerce => 1 support. Yay!

Leave a comment

About Toby Inkster

user-pic I'm tobyink on CPAN, IRC and PerlMonks.