Rants about generalisations notwithstanding, I’m a fan of typeful programming (I’m sure I’d love Ada). For a script that will be moderately complex, I like to sit down and think about the types I’m going to use before I start.
Any library that will enable me to specify my types more precisely and concisely is obviously a win.
And speaking of Moose…
Moose has a bunch of methods to specify your types and a built-in type hierarchy available that you can build off.
Abusing an example I’ve used before:
use Moose; use Moose::Util::TypeConstraints; use MooseX::Params::Validate; subtype 'LegalDrinkingAge' => as 'Int' => where { $_ >= 18 } ; coerce 'LegalDrinkingAge' => from 'Int' => via { 1 } ; sub can_legally_drink { my $age = pos_validated_list( \@_, { isa => 'LegalDrinkingAge' }, ); return 1; } print can_legally_drink(18), "\n"; print can_legally_drink(17), "\n";
Checking for a LegalDrinkingAge type here is obviously the wrong thing to do, but for the purposes of the example it will do.
The resulting error is fine, if a little ugly.
$ perl5.10.1 moose-types.pl
1
Parameter #1 ("17") to main::can_legally_drink did not pass the 'checking type constraint for LegalDrinkingAge' callback
at /u/packages/lib/perl5/site_perl/5.10.1/MooseX/Params/Validate.pm line 168
MooseX::Params::Validate::pos_validated_list('ARRAY(0x976ce40)', 'HASH(0x911b6f8)') called at moose-types.pl line 24
main::can_legally_drink(17) called at moose-types.pl line 33
[…] This post was mentioned on Twitter by Cheng-Lung Sung, Perl Bits. Perl Bits said: Moose Types http://bit.ly/fZd5hF […]