Type::Tiny Tricks #4: Inlined Type Constraints

If ever you're unsure of how a type constraint has been defined, you can examine the string of Perl code used to implement it. For example, does an ArrayRef[Int] accept an empty arrayref?

   my $type = ArrayRef[Int];
   print $type->inline_check('$X');

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;

Type::Tiny Tricks #2: Types Are Objects

When you use code like this:

   package Local::Eg2;
   use Moose;
   use Types::Standard -types;
   
   has foo => (
      is      => "ro",
      isa     => Int,
      coerce  => 1,
   );
   
   __PACKAGE__->meta->make_immutable;

Perhaps you don't think very much about what that bareword Int is actually doing. Well, it's a function that returns a blessed object. This object is used by Moose to check whether values are integers. Yes, Moose uses the object, and you can use it too!

Type::Tiny Tricks #1: Quick Intersections

Type::Tiny objects overload the & (bitwise and) operator to build a type constraint intersection. For example:

   package Local::Eg1;
   use Moose;
   use Types::Standard -types;
   
   has foo => (
      is  => "ro",
      isa => ArrayRef[Int] & HashRef[Int],
   );
   
   __PACKAGE__->meta->make_immutable;

Though that example isn't especially useful. Do you remember Venn diagrammes? Intersections are that small overlapping section in the middle. So the value for foo needs to be something that is simultaneously an arrayref and a hashref. (Which no value could satisfy.)

But there are ways intersections can be used more usefully.

Type::Tiny 1.000000 Released

It's been almost 17 months, and over 160 releases to get there, but Type-Tiny 1.000000 has been released on CPAN Day 2014.

Over the next few days I'll be posting some tips and tricks explaini…