0

我需要检测用户输入的值是否包含正数、非零数。输入字段代表产品数量,并且必须大于零,并且不包含字母或非数字字符。IOW,输入必须只包含这些字符:0123456789 但是当然,零本身是不可接受的。这是我使用代码的方式:

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

谢谢。

4

3 回答 3

4

请记住,像这样1E4的字符串也是数字,因此并非每个数字都必须[0-9]只包含。

提供的looks_like_number函数Scalar::Util是检查变量是否为数字的正确方法。

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

同样的事情更简洁:

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

请注意,像Nan,Inf和之类的字符串Infinity被视为 numeric,因此您可能还需要考虑将这些字符串剔除:

warn "Please enter a whole number for the quantity"
  unless looks_like_number( $fields{quantity} )
         && $fields{quantity} !~ /Inf|NaN/i
         && $fields{quantity} > 0;
于 2013-01-20T12:59:29.683 回答
3

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.";
}
于 2013-01-20T13:44:43.460 回答
2

我相信使用looks_like_numberfrom Scalar::Util更安全,正如@Zaid 指出的答案,但这里有一个正则表达式版本:

if (not defined $fields{'quantity'}) or $fields{'quantity'} !~ /^[0-9]+$/ or $fields{'quantity'} <= 0) {
    $errors .= "Please enter a whole number for the quantity.";
}
于 2013-01-20T13:00:18.227 回答