Why does my Perl routine return false even if the parameters are valid?

I am trying to write a function that checks the username for an alphanumeric value, and in the event of a failure, I should log my user error message and return 0 of the called function instead of die-ing:

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 ";
}

With the above code, I ran into a problem that still returns 0 if successful. Can someone help me in this regard and can someone explain to me why this is done?

+3
source share
1 answer

The callback associated with on_failshould not return a value. Assumed diesomehow.

Params:: Validate documentation on_fail:

on_fail => $callback

, , . , . , , , .

, () . , , .

Carp modess().

( )

, eval:

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
+3

Source: https://habr.com/ru/post/1731546/


All Articles