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

This is a very old article. It has been imported from older blogging software, and the formatting, images, etc may have been lost. Some links may be broken. Some of the information may no longer be correct. Opinions expressed in this article may no longer be held.

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.