perl - 为什么我的 Perl 子例程返回 false,即使参数有效?

标签 perl validation parameters

我正在尝试编写一个函数来验证字母数字值的用户名,如果失败,它应该记录我的自定义错误消息并将 0 返回给被调用的函数而不是死掉:

sub insertUser{
            my ( $username, $password, $email, $name) = validate_pos( @_, 
                   { type => SCALAR,
                     regex => qr/^\w+$/,
                     on_fail => { $err->error("username validation failed"),return 0 }  
                     },
                    { type => SCALAR },
                    { type => SCALAR },
                    { type => SCALAR ,optional => 1,default => 99});
            print "$username, $password, $email, $name ";
}

使用上面的代码,我遇到了一个问题,它在成功案例中仍然返回 0。 任何人都可以在这方面帮助我,任何人都可以向我解释为什么这样做吗?

最佳答案

on_fail 关联的回调不应返回值。它应该以某种方式死亡

Params::Validate documentation , 是on_fail 回调的以下解释:

on_fail => $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 die() internally. If it does not, the validation will proceed onwards, with unpredictable results.

The default is to simply use the Carp module's confess() function.

(强调我的)

以下代码通过将验证例程包装在 eval block 中来工作:

use strict;
use warnings;
use Params::Validate qw{ :all};
my $return_value = insertUser('user','password','user@example.com');  #passes
print "return value: $return_value\n";

my $error_return_value = insertUser('user*','password','user@example.com');  
print "error return value: $error_return_value\n";

sub insertUser{
     eval{
         my ( $username, $password, $email, $name) = validate_pos( @_, 
                { 
                  type    => SCALAR,
                  regex   => qr/^\w+$/,
                  on_fail => sub{ die "username validation failed"},  
                },
                { type => SCALAR },
                { type => SCALAR },
                { type => SCALAR ,optional => 1,default => 99});
         print "$username, $password, $email, $name \n";
     };
     if($@){
         return 0;
     }else{
         return 1;
     }
}

输出结果是:

user, password, user@example.com, 99
return value: 1
error return value: 0

关于perl - 为什么我的 Perl 子例程返回 false,即使参数有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2207375/

相关文章:

java - 这是验证仅 0 和 1 字符串输入的最佳方法吗?

javascript - 如何在 Visual Studio 的起始页上设置 URL 查询参数

parameters - PyCharm 提取参数通常不起作用 : "Cannot perform refactoring using selected element(s)"

perl - Perl 有运行时流程图吗?

xml - 使用 perl 或 awk 从 xml 数据中删除 xml 声明

angularjs - 如果我可以在我的 html 页面中使用 $scope 值,为什么我不能在我的 Controller 中使用它?

javascript - jQuery .submit() 有验证但没有页面刷新

C++非类型模板参数编译时检查

perl - 如何彻底删除 Perl 中的包?

java - 有人可以向我解释线程吗?