Type::Tiny::Manual::Params - coerce and validate arguments to functions and methods
Type::Tiny objects overload coderef calls to assert. For example, the following is a method that takes a string; if the parameters fail their constraints, then an exception will be thrown.
use Types::Standard qw( Str ); use Type::Utils; my $Invocant = class_type { class => __PACKAGE__ }; sub set_name { $Invocant->(my $self = shift); Str->(my $name = shift); ...; }
Alternatively, remember that type libraries also export check (is_*) functions:
is_*
use Types::Standard qw( is_Str ); use Type::Utils; my $Invocant = class_type { class => __PACKAGE__ }; sub set_name { $Invocant->check(my $self = shift) or die; is_Str(my $name = shift) or die; ...; }
... and assertion (assert_*) functions:
assert_*
use Types::Standard qw( assert_Str ); use Type::Utils; my $Invocant = class_type { class => __PACKAGE__ }; sub set_name { $Invocant->assert_valid(my $self = shift); assert_Str(my $name = shift); ...; }
There is a module called Type::Params available to wrap up type coercion and constraint checks into a single, simple and fast check. If you care about speed, this is the way to go...
use feature qw( state ); use Types::Standard qw( Str ); use Type::Utils; use Type::Params qw( compile ); my $Invocant = class_type { class => __PACKAGE__ }; sub set_name { state $check = compile($Invocant, Str); my ($self, $name) = $check->(@_); ...; }
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2013 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
To install Type::Tiny, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Type::Tiny
CPAN shell
perl -MCPAN -e shell install Type::Tiny
For more information on module installation, please visit the detailed CPAN module installation guide.