<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package Params::Validate;
{
  $Params::Validate::VERSION = '1.08';
}

use 5.008001;

use strict;
use warnings;

use Exporter;
use Module::Implementation;
use Params::Validate::Constants;

use vars qw( $NO_VALIDATION %OPTIONS $options );

our @ISA = 'Exporter';

my %tags = (
    types =&gt; [
        qw(
            SCALAR
            ARRAYREF
            HASHREF
            CODEREF
            GLOB
            GLOBREF
            SCALARREF
            HANDLE
            BOOLEAN
            UNDEF
            OBJECT
            )
    ],
);

our %EXPORT_TAGS = (
    'all' =&gt; [
        qw( validate validate_pos validation_options validate_with ),
        map { @{ $tags{$_} } } keys %tags
    ],
    %tags,
);

our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} }, 'set_options' );
our @EXPORT = qw( validate validate_pos );

$NO_VALIDATION = $ENV{PERL_NO_VALIDATION};

{
    my $loader = Module::Implementation::build_loader_sub(
        implementations =&gt; [ 'XS', 'PP' ],
        symbols         =&gt; [
            qw(
                validate
                validate_pos
                validate_with
                validation_options
                set_options
                ),
        ],
    );

    $ENV{PARAMS_VALIDATE_IMPLEMENTATION} = 'PP' if $ENV{PV_TEST_PERL};

    $loader-&gt;();
}

1;

# ABSTRACT: Validate method/function parameters

__END__

=pod

=head1 NAME

Params::Validate - Validate method/function parameters

=head1 VERSION

version 1.08

=head1 SYNOPSIS

    use Params::Validate qw(:all);

    # takes named params (hash or hashref)
    sub foo {
        validate(
            @_, {
                foo =&gt; 1,    # mandatory
                bar =&gt; 0,    # optional
            }
        );
    }

    # takes positional params
    sub bar {
        # first two are mandatory, third is optional
        validate_pos( @_, 1, 1, 0 );
    }

    sub foo2 {
        validate(
            @_, {
                foo =&gt;
                    # specify a type
                    { type =&gt; ARRAYREF },
                bar =&gt;
                    # specify an interface
                    { can =&gt; [ 'print', 'flush', 'frobnicate' ] },
                baz =&gt; {
                    type      =&gt; SCALAR,     # a scalar ...
                                             # ... that is a plain integer ...
                    regex     =&gt; qr/^\d+$/,
                    callbacks =&gt; {           # ... and smaller than 90
                        'less than 90' =&gt; sub { shift() &lt; 90 },
                    },
                }
            }
        );
    }

    sub with_defaults {
        my %p = validate(
            @_, {
                # required
                foo =&gt; 1,
                # $p{bar} will be 99 if bar is not given.  bar is now
                # optional.
                bar =&gt; { default =&gt; 99 }
            }
        );
    }

    sub pos_with_defaults {
        my @p = validate_pos( @_, 1, { default =&gt; 99 } );
    }

    sub sets_options_on_call {
        my %p = validate_with(
            params =&gt; \@_,
            spec   =&gt; { foo =&gt; { type =&gt; SCALAR, default =&gt; 2 } },
            normalize_keys =&gt; sub { $_[0] =~ s/^-//; lc $_[0] },
        );
    }

=head1 DESCRIPTION

The Params::Validate module allows you to validate method or function
call parameters to an arbitrary level of specificity.  At the simplest
level, it is capable of validating the required parameters were given
and that no unspecified additional parameters were passed in.

It is also capable of determining that a parameter is of a specific
type, that it is an object of a certain class hierarchy, that it
possesses certain methods, or applying validation callbacks to
arguments.

=head2 EXPORT

The module always exports the C&lt;validate()&gt; and C&lt;validate_pos()&gt;
functions.

It also has an additional function available for export,
C&lt;validate_with&gt;, which can be used to validate any type of
parameters, and set various options on a per-invocation basis.

In addition, it can export the following constants, which are used as
part of the type checking.  These are C&lt;SCALAR&gt;, C&lt;ARRAYREF&gt;,
C&lt;HASHREF&gt;, C&lt;CODEREF&gt;, C&lt;GLOB&gt;, C&lt;GLOBREF&gt;, and C&lt;SCALARREF&gt;,
C&lt;UNDEF&gt;, C&lt;OBJECT&gt;, C&lt;BOOLEAN&gt;, and C&lt;HANDLE&gt;.  These are explained
in the section on L&lt;Type Validation|Params::Validate/Type Validation&gt;.

The constants are available via the export tag C&lt;:types&gt;.  There is
also an C&lt;:all&gt; tag which includes all of the constants as well as the
C&lt;validation_options()&gt; function.

=head1 PARAMETER VALIDATION

The validation mechanisms provided by this module can handle both
named or positional parameters.  For the most part, the same features
are available for each.  The biggest difference is the way that the
validation specification is given to the relevant subroutine.  The
other difference is in the error messages produced when validation
checks fail.

When handling named parameters, the module will accept either a hash
or a hash reference.

Subroutines expecting named parameters should call the C&lt;validate()&gt;
subroutine like this:

    validate(
        @_, {
            parameter1 =&gt; validation spec,
            parameter2 =&gt; validation spec,
            ...
        }
    );

Subroutines expecting positional parameters should call the
C&lt;validate_pos()&gt; subroutine like this:

    validate_pos( @_, { validation spec }, { validation spec } );

=head2 Mandatory/Optional Parameters

If you just want to specify that some parameters are mandatory and
others are optional, this can be done very simply.

For a subroutine expecting named parameters, you would do this:

    validate( @_, { foo =&gt; 1, bar =&gt; 1, baz =&gt; 0 } );

This says that the "foo" and "bar" parameters are mandatory and that
the "baz" parameter is optional.  The presence of any other
parameters will cause an error.

For a subroutine expecting positional parameters, you would do this:

    validate_pos( @_, 1, 1, 0, 0 );

This says that you expect at least 2 and no more than 4 parameters.
If you have a subroutine that has a minimum number of parameters but
can take any maximum number, you can do this:

    validate_pos( @_, 1, 1, (0) x (@_ - 2) );

This will always be valid as long as at least two parameters are
given.  A similar construct could be used for the more complex
validation parameters described further on.

Please note that this:

    validate_pos( @_, 1, 1, 0, 1, 1 );

makes absolutely no sense, so don't do it.  Any zeros must come at the
end of the validation specification.

In addition, if you specify that a parameter can have a default, then
it is considered optional.

=head2 Type Validation

This module supports the following simple types, which can be
L&lt;exported as constants|/EXPORT&gt;:

=over 4

=item * SCALAR

A scalar which is not a reference, such as C&lt;10&gt; or C&lt;'hello'&gt;.  A
parameter that is undefined is B&lt;not&gt; treated as a scalar.  If you
want to allow undefined values, you will have to specify C&lt;SCALAR |
UNDEF&gt;.

=item * ARRAYREF

An array reference such as C&lt;[1, 2, 3]&gt; or C&lt;\@foo&gt;.

=item * HASHREF

A hash reference such as C&lt;&lt; { a =&gt; 1, b =&gt; 2 } &gt;&gt; or C&lt;\%bar&gt;.

=item * CODEREF

A subroutine reference such as C&lt;\&amp;foo_sub&gt; or C&lt;sub { print "hello" }&gt;.

=item * GLOB

This one is a bit tricky.  A glob would be something like C&lt;*FOO&gt;, but
not C&lt;\*FOO&gt;, which is a glob reference.  It should be noted that this
trick:

    my $fh = do { local *FH; };

makes C&lt;$fh&gt; a glob, not a glob reference.  On the other hand, the
return value from C&lt;Symbol::gensym&gt; is a glob reference.  Either can
be used as a file or directory handle.

=item * GLOBREF

A glob reference such as C&lt;\*FOO&gt;.  See the L&lt;GLOB|GLOB&gt; entry above
for more details.

=item * SCALARREF

A reference to a scalar such as C&lt;\$x&gt;.

=item * UNDEF

An undefined value

=item * OBJECT

A blessed reference.

=item * BOOLEAN

This is a special option, and is just a shortcut for C&lt;UNDEF | SCALAR&gt;.

=item * HANDLE

This option is also special, and is just a shortcut for C&lt;GLOB |
GLOBREF&gt;.  However, it seems likely that most people interested in
either globs or glob references are likely to really be interested in
whether the parameter in question could be a valid file or directory
handle.

=back

To specify that a parameter must be of a given type when using named
parameters, do this:

    validate(
        @_, {
            foo =&gt; { type =&gt; SCALAR },
            bar =&gt; { type =&gt; HASHREF }
        }
    );

If a parameter can be of more than one type, just use the bitwise or
(C&lt;|&gt;) operator to combine them.

    validate( @_, { foo =&gt; { type =&gt; GLOB | GLOBREF } );

For positional parameters, this can be specified as follows:

    validate_pos( @_, { type =&gt; SCALAR | ARRAYREF }, { type =&gt; CODEREF } );

=head2 Interface Validation

To specify that a parameter is expected to have a certain set of
methods, we can do the following:

    validate(
        @_, {
            foo =&gt;
                # just has to be able to -&gt;bar
                { can =&gt; 'bar' }
        }
    );

 ... or ...

    validate(
        @_, {
            foo =&gt;
                # must be able to -&gt;bar and -&gt;print
                { can =&gt; [qw( bar print )] }
        }
    );

=head2 Class Validation

A word of warning.  When constructing your external interfaces, it is
probably better to specify what methods you expect an object to
have rather than what class it should be of (or a child of).  This
will make your API much more flexible.

With that said, if you want to validate that an incoming parameter
belongs to a class (or child class) or classes, do:

    validate(
        @_,
        { foo =&gt; { isa =&gt; 'My::Frobnicator' } }
    );

 ... or ...

    validate(
        @_,
        # must be both, not either!
        { foo =&gt; { isa =&gt; [qw( My::Frobnicator IO::Handle )] } }
    );

=head2 Regex Validation

If you want to specify that a given parameter must match a specific
regular expression, this can be done with "regex" spec key.  For
example:

    validate(
        @_,
        { foo =&gt; { regex =&gt; qr/^\d+$/ } }
    );

The value of the "regex" key may be either a string or a pre-compiled
regex created via C&lt;qr&gt;.

If the value being checked against a regex is undefined, the regex is
explicitly checked against the empty string ('') instead, in order to
avoid "Use of uninitialized value" warnings.

The C&lt;Regexp::Common&gt; module on CPAN is an excellent source of regular
expressions suitable for validating input.

=head2 Callback Validation

If none of the above are enough, it is possible to pass in one or more
callbacks to validate the parameter.  The callback will be given the
B&lt;value&gt; of the parameter as its first argument.  Its second argument
will be all the parameters, as a reference to either a hash or array.
Callbacks are specified as hash reference.  The key is an id for the
callback (used in error messages) and the value is a subroutine
reference, such as:

    validate(
        @_, {
            foo =&gt; {
                callbacks =&gt; {
                    'smaller than a breadbox' =&gt; sub { shift() &lt; $breadbox },
                    'green or blue' =&gt;
                        sub { $_[0] eq 'green' || $_[0] eq 'blue' }
                }
            }
        );

    validate(
        @_, {
            foo =&gt; {
                callbacks =&gt; {
                    'bigger than baz' =&gt; sub { $_[0] &gt; $_[1]-&gt;{baz} }
                }
            }
        }
    );

=head2 Untainting

If you want values untainted, set the "untaint" key in a spec hashref
to a true value, like this:

    my %p = validate(
        @_, {
            foo =&gt; { type =&gt; SCALAR, untaint =&gt; 1 },
            bar =&gt; { type =&gt; ARRAYREF }
        }
    );

This will untaint the "foo" parameter if the parameters are valid.

Note that untainting is only done if I&lt;all parameters&gt; are valid.
Also, only the return values are untainted, not the original values
passed into the validation function.

Asking for untainting of a reference value will not do anything, as
C&lt;Params::Validate&gt; will only attempt to untaint the reference itself.

=head2 Mandatory/Optional Revisited

If you want to specify something such as type or interface, plus the
fact that a parameter can be optional, do this:

    validate(
        @_, {
            foo =&gt; { type =&gt; SCALAR },
            bar =&gt; { type =&gt; ARRAYREF, optional =&gt; 1 }
        }
    );

or this for positional parameters:

    validate_pos(
        @_,
        { type =&gt; SCALAR },
        { type =&gt; ARRAYREF, optional =&gt; 1 }
    );

By default, parameters are assumed to be mandatory unless specified as
optional.

=head2 Dependencies

It also possible to specify that a given optional parameter depends on
the presence of one or more other optional parameters.

    validate(
        @_, {
            cc_number =&gt; {
                type     =&gt; SCALAR,
                optional =&gt; 1,
                depends  =&gt; [ 'cc_expiration', 'cc_holder_name' ],
            },
            cc_expiration  { type =&gt; SCALAR, optional =&gt; 1 },
            cc_holder_name { type =&gt; SCALAR, optional =&gt; 1 },
        }
    );

In this case, "cc_number", "cc_expiration", and "cc_holder_name" are
all optional.  However, if "cc_number" is provided, then
"cc_expiration" and "cc_holder_name" must be provided as well.

This allows you to group together sets of parameters that all must be
provided together.

The C&lt;validate_pos()&gt; version of dependencies is slightly different,
in that you can only depend on one other parameter.  Also, if for
example, the second parameter 2 depends on the fourth parameter, then
it implies a dependency on the third parameter as well.  This is
because if the fourth parameter is required, then the user must also
provide a third parameter so that there can be four parameters in
total.

C&lt;Params::Validate&gt; will die if you try to depend on a parameter not
declared as part of your parameter specification.

=head2 Specifying defaults

If the C&lt;validate()&gt; or C&lt;validate_pos()&gt; functions are called in a list
context, they will return a hash or containing the original parameters plus
defaults as indicated by the validation spec.

If the function is not called in a list context, providing a default
in the validation spec still indicates that the parameter is optional.

The hash or array returned from the function will always be a copy of
the original parameters, in order to leave C&lt;@_&gt; untouched for the
calling function.

Simple examples of defaults would be:

    my %p = validate( @_, { foo =&gt; 1, bar =&gt; { default =&gt; 99 } } );

    my @p = validate_pos( @_, 1, { default =&gt; 99 } );

In scalar context, a hash reference or array reference will be
returned, as appropriate.

=head1 USAGE NOTES

=head2 Validation failure

By default, when validation fails C&lt;Params::Validate&gt; calls
C&lt;Carp::confess()&gt;.  This can be overridden by setting the C&lt;on_fail&gt;
option, which is described in the L&lt;"GLOBAL" OPTIONS|"GLOBAL" OPTIONS&gt;
section.

=head2 Method calls

When using this module to validate the parameters passed to a method
call, you will probably want to remove the class/object from the
parameter list B&lt;before&gt; calling C&lt;validate()&gt; or C&lt;validate_pos()&gt;.
If your method expects named parameters, then this is necessary for
the C&lt;validate()&gt; function to actually work, otherwise C&lt;@_&gt; will not
be usable as a hash, because it will first have your object (or
class) B&lt;followed&gt; by a set of keys and values.

Thus the idiomatic usage of C&lt;validate()&gt; in a method call will look
something like this:

    sub method {
        my $self = shift;

        my %params = validate(
            @_, {
                foo =&gt; 1,
                bar =&gt; { type =&gt; ARRAYREF },
            }
        );
    }

=head2 Speeding Up Validation

In most cases, the validation spec will remain the same for each call to a
subroutine. In that case, you can speed up validation by defining the
validation spec just once, rather than on each call to the subroutine:

    my %spec = ( ... );
    sub foo {
        my %params = validate( @_, \%spec );
    }

You can also use the C&lt;state&gt; feature to do this:

    use feature 'state';

    sub foo {
        state $spec = { ... };
        my %params = validate( @_, $spec );
    }

=head1 "GLOBAL" OPTIONS

Because the API for the C&lt;validate()&gt; and C&lt;validate_pos()&gt; functions does not
make it possible to specify any options other than the validation spec, it is
possible to set some options as pseudo-'globals'.  These allow you to specify
such things as whether or not the validation of named parameters should be
case sensitive, for one example.

These options are called pseudo-'globals' because these settings are
B&lt;only applied to calls originating from the package that set the
options&gt;.

In other words, if I am in package C&lt;Foo&gt; and I call
C&lt;validation_options()&gt;, those options are only in effect when I call
C&lt;validate()&gt; from package C&lt;Foo&gt;.

While this is quite different from how most other modules operate, I
feel that this is necessary in able to make it possible for one
module/application to use Params::Validate while still using other
modules that also use Params::Validate, perhaps with different
options set.

The downside to this is that if you are writing an app with a standard
calling style for all functions, and your app has ten modules, B&lt;each
module must include a call to C&lt;validation_options()&gt;&gt;. You could of
course write a module that all your modules use which uses various
trickery to do this when imported.

=head2 Options

=over 4

=item * normalize_keys =&gt; $callback

This option is only relevant when dealing with named parameters.

This callback will be used to transform the hash keys of both the
parameters and the parameter spec when C&lt;validate()&gt; or
C&lt;validate_with()&gt; are called.

Any alterations made by this callback will be reflected in the
parameter hash that is returned by the validation function.  For
example:

    sub foo {
        return validate_with(
            params =&gt; \@_,
            spec   =&gt; { foo =&gt; { type =&gt; SCALAR } },
            normalize_keys =&gt;
                sub { my $k = shift; $k =~ s/^-//; return uc $k },
        );

    }

    %p = foo( foo =&gt; 20 );

    # $p{FOO} is now 20

    %p = foo( -fOo =&gt; 50 );

    # $p{FOO} is now 50

The callback must return a defined value.

If a callback is given then the deprecated "ignore_case" and
"strip_leading" options are ignored.

=item * allow_extra =&gt; $boolean

If true, then the validation routine will allow extra parameters not
named in the validation specification.  In the case of positional
parameters, this allows an unlimited number of maximum parameters
(though a minimum may still be set).  Defaults to false.

=item * on_fail =&gt; $callback

If given, this callback will be called whenever a validation check
fails.  It will be called with a single parameter, which will be a
string describing the failure.  This is useful if you wish to have
this module throw exceptions as objects rather than as strings, for
example.

This callback is expected to C&lt;die()&gt; internally.  If it does not, the
validation will proceed onwards, with unpredictable results.

The default is to simply use the Carp module's C&lt;confess()&gt; function.

=item * stack_skip =&gt; $number

This tells Params::Validate how many stack frames to skip when finding
a subroutine name to use in error messages.  By default, it looks one
frame back, at the immediate caller to C&lt;validate()&gt; or
C&lt;validate_pos()&gt;.  If this option is set, then the given number of
frames are skipped instead.

=item * ignore_case =&gt; $boolean

DEPRECATED

This is only relevant when dealing with named parameters.  If it is
true, then the validation code will ignore the case of parameter
names.  Defaults to false.

=item * strip_leading =&gt; $characters

DEPRECATED

This too is only relevant when dealing with named parameters.  If this
is given then any parameters starting with these characters will be
considered equivalent to parameters without them entirely.  For
example, if this is specified as '-', then C&lt;-foo&gt; and C&lt;foo&gt; would be
considered identical.

=back

=head1 PER-INVOCATION OPTIONS

The C&lt;validate_with()&gt; function can be used to set the options listed
above on a per-invocation basis.  For example:

    my %p = validate_with(
        params =&gt; \@_,
        spec   =&gt; {
            foo =&gt; { type    =&gt; SCALAR },
            bar =&gt; { default =&gt; 10 }
        },
        allow_extra =&gt; 1,
    );

In addition to the options listed above, it is also possible to set
the option "called", which should be a string.  This string will be
used in any error messages caused by a failure to meet the validation
spec.

This subroutine will validate named parameters as a hash if the "spec"
parameter is a hash reference.  If it is an array reference, the
parameters are assumed to be positional.

    my %p = validate_with(
        params =&gt; \@_,
        spec   =&gt; {
            foo =&gt; { type    =&gt; SCALAR },
            bar =&gt; { default =&gt; 10 }
        },
        allow_extra =&gt; 1,
        called      =&gt; 'The Quux::Baz class constructor',
    );

    my @p = validate_with(
        params =&gt; \@_,
        spec   =&gt; [
            { type    =&gt; SCALAR },
            { default =&gt; 10 }
        ],
        allow_extra =&gt; 1,
        called      =&gt; 'The Quux::Baz class constructor',
    );

=head1 DISABLING VALIDATION

If the environment variable C&lt;PERL_NO_VALIDATION&gt; is set to something
true, then validation is turned off.  This may be useful if you only
want to use this module during development but don't want the speed
hit during production.

The only error that will be caught will be when an odd number of
parameters are passed into a function/method that expects a hash.

If you want to selectively turn validation on and off at runtime, you
can directly set the C&lt;$Params::Validate::NO_VALIDATION&gt; global
variable.  It is B&lt;strongly&gt; recommended that you B&lt;localize&gt; any
changes to this variable, because other modules you are using may
expect validation to be on when they execute.  For example:

    {
        local $Params::Validate::NO_VALIDATION = 1;

        # no error
        foo( bar =&gt; 2 );
    }

    # error
    foo( bar =&gt; 2 );

    sub foo {
        my %p = validate( @_, { foo =&gt; 1 } );
        ...;
    }

But if you want to shoot yourself in the foot and just turn it off, go
ahead!

=head1 LIMITATIONS

Right now there is no way (short of a callback) to specify that
something must be of one of a list of classes, or that it must possess
one of a list of methods.  If this is desired, it can be added in the
future.

Ideally, there would be only one validation function.  If someone
figures out how to do this, please let me know.

=head1 SUPPORT

Please submit bugs and patches to the CPAN RT system at
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Params%3A%3AValidate or
via email at bug-params-validate@rt.cpan.org.

Support questions can be sent to Dave at autarch@urth.org.

=head1 DONATIONS

If you'd like to thank me for the work I've done on this module,
please consider making a "donation" to me via PayPal. I spend a lot of
free time creating free software, and would appreciate any support
you'd care to offer.

Please note that B&lt;I am not suggesting that you must do this&gt; in order
for me to continue working on this particular software. I will
continue to do so, inasmuch as I have in the past, for as long as it
interests me.

Similarly, a donation made in this way will probably not make me work
on this software much more, unless I get so many donations that I can
consider working on free software full time, which seems unlikely at
best.

To donate, log into PayPal and send money to autarch@urth.org or use
the button on this page:
L&lt;http://www.urth.org/~autarch/fs-donation.html&gt;

=head1 AUTHOR

Dave Rolsky, &lt;autarch@urth.org&gt; and Ilya Martynov &lt;ilya@martynov.org&gt;

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2013 by Dave Rolsky and Ilya Martynov.

This is free software, licensed under:

  The Artistic License 2.0 (GPL Compatible)

=cut
</pre></body></html>