Validating parameters

Manual

To get started with Type::Params, please read Type::Tiny::Manual::UsingWithMoo which will cover a lot of the basics, even if you're not using Moo.

multiple

The multiple option allows you to specify multiple ways of calling a sub.

  signature_for repeat_string => (
    multiple => [
      { positional => [ Str, Int ] },
      { named => [ string => Str, count => Int ], named_to_list => true },
    ],
  );
  
  sub repeat_string ( $string, $count ) {
    return $string x $count;
  }
  
  repeat_string(            "Hello",          42  );    # works
  repeat_string(  string => "Hello", count => 42  );    # works
  repeat_string({ string => "Hello", count => 42 });    # works
  repeat_string( qr/hiya/ );                            # dies

It combines multiple checks and tries each until one works.

list_to_named

In many cases, the multiple call conventions offered by multiple can be implemented more easily using list_to_named .

  signature_for repeat_string => (
    list_to_named => true,
    named         => [ string => Str, count => Int ],
    named_to_list => true,
  );
  
  sub repeat_string ( $string, $count ) {
    return $string x $count;
  }
  
  # Standard ways to call the function:
  repeat_string(  string => "Hello", count => 42  );
  repeat_string({ string => "Hello", count => 42 });
  
  # These should also work:
  repeat_string( "Hello", count => 42 );
  repeat_string( "Hello", { count => 42 } );
  repeat_string( 42, string => "Hello" );
  repeat_string( 42, { string => "Hello" } );
  repeat_string( "Hello", 42 );
  
  # This currently won't work though, because "42" appears first so is taken
  # to be the string, but "Hello" isn't a valid integer!
  repeat_string( 42, "Hello" );

The list_to_named option works in three stages. When looking for the hash or hashref of named parameters, if there are other parameters first, these are kept to one side in a list of "sneaky" positional parameters.

Later when validating the named parameters, if any of them seem to be missing, the list of sneaky positional parameters is examined and if possible the parameter is taken from there.

Finally after all the named parameters have been processed, if there are still any positional parameters which weren't needed, an error is thrown.

signature

signature allows the signature to be defined within the sub itself, potentially on-the-fly, which is occasionally useful.

Instead of this:

  signature_for foobar => (
    positional => [ Int, Str ],
  );
  
  sub foobar ( $foo, $bar ) {
    ...;
  }

You do this:

  sub foobar {
    my $check = signature( positional => [ Int, Str ] );
    my ( $foo, $bar ) = $check->( @_ );
    ...;
  }

Or use state $check if you know the check will be the same every time.

Functions versus Methods

For subs which are intended to be called as functions:

  signature_for my_sub => ( method => false, ... );
  
  signature_for my_sub => ( ... ); # this is the default anyway

For subs which are intended to be called as methods on a blessed object:

  signature_for my_method => ( method => Object, ... );

And for subs which are intended to be called as methods on a class:

  signature_for my_method => ( method => ClassName, ... );
  
  signature_for my_method => ( method => Str, ... );  # faster, less readable

The following are also allowed, which indicates that the sub is intended to be called as a method, but you don't want to do type checks on the invocant:

  signature_for my_method => ( method => builtin::true, ... );
  
  signature_for my_method => ( method => 1, ... );

Shortcuts are available:

  use Type::Params qw( signature_for_func signature_for_method );
  
  signature_for_func my_function => ( ... );
  
  signature_for_method my_method => ( ... );

Mixed Named and Positional Parameters

The head and tail options allow required positional parameters at the start or end of a named parameter list:

  signature_for my_func => (
    head  => [ Int ],
    named => [
      foo => Int,
      bar => Optional[Int],
      baz => Optional[Int],
    ],
  );
  
  my_func( 42, foo => 21 );                 # ok
  my_func( 42, foo => 21, bar  => 84 );     # ok
  my_func( 42, foo => 21, bar  => 10.5 );   # not ok
  my_func( 42, foo => 21, quux => 84 );     # not ok

Alternatively, list_to_named (see above) may be of use.

Proper Signatures

Don't you wish your subs could look like this?

  sub set_name ( Object $self, Str $name ) {
    $self->{name} = $name;
  }

Well; here are a few solutions for sub signatures that work with Type::Tiny ...

Zydeco

Zydeco is a Perl OO syntax toolkit with Type::Tiny support baked in throughout.

  package MyApp {
    use Zydeco;
    
    class Person {
      has name ( type => Str );
      
      method rename ( Str $new_name ) {
        printf( "%s will now be called %s\n", $self->name, $new_name );
        $self->name( $new_name );
      }
      
      coerce from Str via {
        $class->new( name => $_ )
      }
    }
    
    class Company {
      has owner ( type => 'Person' );
    }
  }
  
  my $acme = MyApp->new_company( owner => "Robert" );
  $acme->owner->rename( "Bob" );

Kavorka

Kavorka is a sub signatures implementation written to natively use Type::Utils ' dwim_type for type constraints, and take advantage of Type::Tiny's features such as inlining, and coercions.

  method set_name ( Str $name ) {
    $self->{name} = $name;
  }

Kavorka's signatures provide a lot more flexibility, and slightly more speed than Type::Params. (The speed comes from inlining almost all type checks into the body of the sub being declared.)

Kavorka also includes support for type checking of the returned value.

Kavorka can also be used as part of Moops , a larger framework for object oriented programming in Perl.

Function::Parameters

Function::Parameters offers support for Type::Tiny and MooseX::Types.

  use Types::Standard qw( Str );
  use Function::Parameters;
  
  method set_name ( Str $name ) {
      $self->{name} = $name;
  }

Attribute::Contract

Both Kavorka and Function::Parameters require a relatively recent version of Perl. Attribute::Contract supports older versions by using a lot less magic.

You want Attribute::Contract 0.03 or above.

  use Attribute::Contract -types => [qw/Object Str/];
  
  sub set_name :ContractRequires(Object, Str) {
      my ($self, $name) = @_;
      $self->{name} = $name;
  }

Attribute::Contract also includes support for type checking of the returned value.

Type::Params versus X

Params::Validate

Type::Params is not really a drop-in replacement for Params::Validate ; the API differs far too much to claim that. Yet it performs a similar task, so it makes sense to compare them.

Params::ValidationCompiler

Params::ValidationCompiler does basically the same thing as Type::Params .

Next Steps

Here's your next step: