Try downloading and installing my Type-Tiny distribution from the CPAN, which offers various type checks and is strongly modelled on the Moose type constraint system.
You can do type checks like:
use Types::Standard qw( Int );
if ( not Int->check($var) ) {
die "It's supposed to be an integer!\n";
}
The check method shown above will return a boolean. There's also an assert_return method. This will spew out its own error message if the value doesn't pass its type check, so you don't need to do the if not ... die stuff. (And if the value does pass, it simply returns it.)
use Types::Standard qw( Int );
Int->assert_valid($var);
Here's how you could do the type checks for a function:
use Types::Standard qw( Object Num );
sub transfer_money {
my $from_account = Object->assert_return( shift );
my $to_account = Object->assert_return( shift );
my $amount = Num->assert_return( shift );
...;
}
One of the other modules that is bundled along with it is called Type::Params, and simplifies type checks for functions even more, and is pretty damn fast.
use feature qw( state ); # enable the `state` feature from Perl 5.10+
use Types::Standard qw( Object Num );
use Type::Params qw( compile );
sub transfer_money {
state $check = compile( Object, Object, Num );
my ($from_account, $to_account, $amount) = $check->(@_);
...;
}
Even if you decide against using it in your final code, it might help you learn how to do various type checks. For example, if you want to know how to test if $val is an integer or not, you can do:
perl -MTypes::Standard=-all -le'print Int->inline_check(q($val))'
This will print out a string of Perl code that shows you how Types::Standard does the check.
|