简体   繁体   中英

How can I test if a Perl string contains a non-negative number?

I need to detect whether a value input by a user contains a positive, non-zero number. The input field represents a product quantity, and must be greater than zero, and contain no alpha or non-numeric characters. IOW, the input must contains only these characters: 0123456789 But of course, zero by itself is not acceptable. Here's how I am using the code:

  if( $fields{'quantity'} =~ [this is where I am unsure]  )
  {
    $errors .= "Please enter a whole number for the quantity.";
  }

Thanks.

Remember that strings like 1E4 are also numeric, so not every number has to contain [0-9] only.

The looks_like_number function provided by Scalar::Util is the Right Way to check if a variable is numeric.

use Scalar::Util 'looks_like_number';

if ( not looks_like_number( $fields{quantity} ) or $fields{quantity} <= 0 ) {

    warn "Please enter a whole number for the quantity";
}

The same thing more succinctly:

warn "Please enter a whole number for the quantity"
  unless looks_like_number( $fields{quantity} )
         && $fields{quantity} > 0;

Be warned that strings like Nan , Inf and Infinity are also deemed numeric , so you may want to consider weeding those out as well:

warn "Please enter a whole number for the quantity"
  unless looks_like_number( $fields{quantity} )
         && $fields{quantity} !~ /Inf|NaN/i
         && $fields{quantity} > 0;

There really is no need to allow for exotics like 1E4 in the input: just make them type a string of digits.

Also, checking for the truth of the value entered will weed out undef , zero, and the empty string, so this will work fine. It checks that the input is defined, non-empty, non-zero, and contains no non-numeric characters.

unless ($fields{quantity} and $fields{quantity} !~ /\D/) {
  $errors .= "Please enter a whole number for the quantity.";
}

I believe it is safer to use the looks_like_number from Scalar::Util as the answer by @Zaid pointed out, but here's a regexp version:

if (not defined $fields{'quantity'}) or $fields{'quantity'} !~ /^[0-9]+$/ or $fields{'quantity'} <= 0) {
    $errors .= "Please enter a whole number for the quantity.";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM