gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:04:21 24 4
gpt4 key购买 nike

我正在尝试编写一个函数来验证字母数字值的用户名,如果失败,它应该记录我的自定义错误消息并将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com