⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 validate.pm

📁 1. 记录每个帖子的访问人情况
💻 PM
📖 第 1 页 / 共 2 页
字号:
 validate( @_,           { foo =>             callbacks =>             { 'smaller than a breadbox' => sub { shift() < $breadbox },               'green or blue' =>                sub { $_[0] eq 'green' || $_[0] eq 'blue' } } } ); validate( @_,           { foo =>             callbacks =>             { 'bigger than baz' => sub { $_[0] > $_[1]->{baz} } } } );=head2 UntaintingIf you want values untainted, set the "untaint" key in a spec hashrefto a true value, like this: my %p =   validate( @_, { foo =>                   { type => SCALAR, untaint => 1 },                   bar =>                   { type => ARRAYREF } } );This will untaint the "foo" parameter if the parameters are valid.Note that untainting is only done if I<all parameters> are valid.Also, only the return values are untainted, not the original valuespassed into the validation function.Asking for untainting of a reference value will not do anything, asC<Params::Validate> will only attempt to untaint the reference itself.=head2 Mandatory/Optional RevisitedIf you want to specify something such as type or interface, plus thefact that a parameter can be optional, do this: validate( @_, { foo =>                 { type => SCALAR },                 bar =>                 { type => ARRAYREF, optional => 1 } } );or this for positional parameters: validate_pos( @_, { type => SCALAR }, { type => ARRAYREF, optional => 1 } );By default, parameters are assumed to be mandatory unless specified asoptional.=head2 DependenciesIt also possible to specify that a given optional parameter depends onthe presence of one or more other optional parameters. validate( @_, { cc_number =>                 { type => SCALAR, optional => 1,                   depends => [ 'cc_expiration', 'cc_holder_name' ],                 },                 cc_expiration                 { type => SCALAR, optional => 1 },                 cc_holder_name                 { type => SCALAR, optional => 1 },               } );In this case, "cc_number", "cc_expiration", and "cc_holder_name" areall 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 beprovided together.The C<validate_pos()> version of dependencies is slightly different,in that you can only depend on one other parameter.  Also, if forexample, the second parameter 2 depends on the fourth parameter, thenit implies a dependency on the third parameter as well.  This isbecause if the fourth parameter is required, then the user must alsoprovide a third parameter so that there can be four parameters intotal.C<Params::Validate> will die if you try to depend on a parameter notdeclared as part of your parameter specification.=head2 Specifying defaultsIf the C<validate()> or C<validate_pos()> functions are called in alist context, they will return an array or hash containing theoriginal parameters plus defaults as indicated by the validation spec.If the function is not called in a list context, providing a defaultin the validation spec still indicates that the parameter is optional.The hash or array returned from the function will always be a copy ofthe original parameters, in order to leave C<@_> untouched for thecalling function.Simple examples of defaults would be: my %p = validate( @_, { foo => 1, bar => { default => 99 } } ); my @p = validate( @_, 1, { default => 99 } );In scalar context, a hash reference or array reference will bereturned, as appropriate.=head1 USAGE NOTES=head2 Validation failureBy default, when validation fails C<Params::Validate> callsC<Carp::confess()>.  This can be overridden by setting the C<on_fail>option, which is described in the L<"GLOBAL" OPTIONS|"GLOBAL" OPTIONS>section.=head2 Method callsWhen using this module to validate the parameters passed to a methodcall, you will probably want to remove the class/object from theparameter list B<before> calling C<validate()> or C<validate_pos()>.If your method expects named parameters, then this is necessary forthe C<validate()> function to actually work, otherwise C<@_> will notbe useable as a hash, because it will first have your object (orclass) B<followed> by a set of keys and values.Thus the idiomatic usage of C<validate()> in a method call will looksomething like this: sub method {     my $self = shift;     my %params = validate( @_, { foo => 1, bar => { type => ARRAYREF } } ); }=head1 "GLOBAL" OPTIONSBecause the calling syntax for the C<validate()> and C<validate_pos()>functions does not make it possible to specify any options other thanthe the validation spec, it is possible to set some options aspseudo-'globals'.  These allow you to specify such things as whetheror not the validation of named parameters should be case sensitive,for one example.These options are called pseudo-'globals' because these settings areB<only applied to calls originating from the package that set theoptions>.In other words, if I am in package C<Foo> and I callC<Params::Validate::validation_options()>, those options are only ineffect when I call C<validate()> from package C<Foo>.While this is quite different from how most other modules operate, Ifeel that this is necessary in able to make it possible for onemodule/application to use Params::Validate while still using othermodules that also use Params::Validate, perhaps with differentoptions set.The downside to this is that if you are writing an app with a standardcalling style for all functions, and your app has ten modules, B<eachmodule must include a call toC<Params::Validate::validation_options()>>.=head2 Options=over 4=item * normalize_keys => $callbackThis option is only relevant when dealing with named parameters.This callback will be used to transform the hash keys of both theparameters and the parameter spec when C<validate()> orC<validate_with()> are called.Any alterations made by this callback will be reflected in theparameter hash that is returned by the validation function.  Forexample:  sub foo {      return        validate_with( params => \@_,                       spec   => { foo => { type => SCALAR } },                       normalize_keys =>                       sub { my $k = shift; $k =~ s/^-//; return uc $k },                     );  }  %p = foo( foo => 20 );  # $p{FOO} is now 20  %p = foo( -fOo => 50 );  # $p{FOO} is now 50The callback must return a defined value.If a callback is given than the deprecated "ignore_case" and"strip_leading" options are ignored.=item * allow_extra => $booleanIf true, then the validation routine will allow extra parameters notnamed in the validation specification.  In the case of positionalparameters, this allows an unlimited number of maximum parameters(though a minimum may still be set).  Defaults to false.=item * on_fail => $callbackIf given, this callback will be called whenever a validation checkfails.  It will be called with a single parameter, which will be astring describing the failure.  This is useful if you wish to havethis module throw exceptions as objects rather than as strings, forexample.This callback is expected to C<die()> internally.  If it does not, thevalidation will proceed onwards, with unpredictable results.The default is to simply use the Carp module's C<confess()> function.=item * stack_skip => $numberThis tells Params::Validate how many stack frames to skip when findinga subroutine name to use in error messages.  By default, it looks oneframe back, at the immediate caller to C<validate()> orC<validate_pos()>.  If this option is set, then the given number offrames are skipped instead.=item * ignore_case => $booleanDEPRECATEDThis is only relevant when dealing with named parameters.  If it istrue, then the validation code will ignore the case of parameternames.  Defaults to false.=item * strip_leading => $charactersDEPRECATEDThis too is only relevant when dealing with named parameters.  If thisis given then any parameters starting with these characters will beconsidered equivalent to parameters without them entirely.  Forexample, if this is specified as '-', then C<-foo> and C<foo> would beconsidered identical.=back=head1 PER-INVOCATION OPTIONSThe C<validate_with()> function can be used to set the options listedabove on a per-invocation basis.  For example:  my %p =      validate_with          ( params => \@_,            spec   => { foo => { type => SCALAR },                        bar => { default => 10 } },            allow_extra => 1,          );In addition to the options listed above, it is also possible to setthe option "called", which should be a string.  This string will beused in any error messages caused by a failure to meet the validationspec.This subroutine will validate named parameters as a hash if the "spec"parameter is a hash reference.  If it is an array reference, theparameters are assumed to be positional.  my %p =      validate_with          ( params => \@_,            spec   => { foo => { type => SCALAR },                        bar => { default => 10 } },            allow_extra => 1,            called => 'The Quux::Baz class constructor',          );  my @p =      validate_with          ( params => \@_,            spec   => [ { type => SCALAR },                        { default => 10 } ],            allow_extra => 1,            called => 'The Quux::Baz class constructor',          );=head1 DISABLING VALIDATIONIf the environment variable C<PERL_NO_VALIDATION> is set to somethingtrue, then validation is turned off.  This may be useful if you onlywant to use this module during development but don't want the speedhit during production.The only error that will be caught will be when an odd number ofparameters are passed into a function/method that expects a hash.If you want to selectively turn validation on and off at runtime, youcan directly set the C<$Params::Validate::NO_VALIDATION> globalvariable.  It is B<strongly> recommended that you B<localize> anychanges to this variable, because other modules you are using mayexpect validation to be on when they execute.  For example:  {      local $Params::Validate::NO_VALIDATION = 1;      # no error      foo( bar => 2 );  }  # error  foo( bar => 2 );  sub foo  {      my %p = validate( @_, { foo => 1 } );      ...  }But if you want to shoot yourself in the foot and just turn it off, goahead!=head1 LIMITATIONSRight now there is no way (short of a callback) to specify thatsomething must be of one of a list of classes, or that it must possessone of a list of methods.  If this is desired, it can be added in thefuture.Ideally, there would be only one validation function.  If someonefigures out how to do this, please let me know.=head1 SUPPORTFor now, support questions should be sent to Dave at autarch@urth.org.The CVS repository is on Savannah athttps://savannah.nongnu.org/projects/p-v-perl/.=head1 SEE ALSOGetargs::Long - similar capabilities with a different interface.  Ifyou like what Params::Validate does but not its 'feel' try this oneinstead.Carp::Assert and Class::Contract - other modules in the general spiritof validating that certain things are true before/while/afterexecuting actual program code.=head1 AUTHORSDave Rolsky, <autarch@urth.org> and Ilya Martynov <ilya@martynov.org>=head1 COPYRIGHTCopyright (c) 2004 David Rolsky.  All rights reserved.  This programis free software; you can redistribute it and/or modify it under thesame terms as Perl itself.=cut

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -