How to validate number in perl? -


i know there library that

use scalar::util qw(looks_like_number);

yet want using perl regular expression. , want work double numbers not integers.

so want better this

$var =~ /^[+-]?\d+$/

thanks.

constructing single regular expression validate number difficult. there many criteria consider. perlfaq4 contains section "how determine whether scalar number/whole/integer/float?

the code documentation shows following tests:

if (/\d/)                          {print "has nondigits\n"      } if (/^\d+$/)                       {print "is whole number\n"  } if (/^-?\d+$/)                     {print "is integer\n"      } if (/^[+-]?\d+$/)                  {print "is +/- integer\n"   } if (/^-?\d+\.?\d*$/)               {print "is real number\n"   } if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) {print "is decimal number\n"} if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([ee]([+-]?\d+))?$/) {     print "is c float\n" } 
  • the first test disqualifies unsigned integer.
  • the second test qualifies whole number.
  • the third test qualifies integer.
  • the fourth test qualifies positive/negatively signed integer.
  • the fifth test qualifies real number.
  • the sixth test qualifies decimal number.
  • the seventh test qualifies number in c-style scientific notation.

so if using tests (excluding first one) have verify 1 or more of tests passes. you've got number.

another method, since don't want use module scalar::util, can learn code in scalar::util. looks_like_number() function set this:

sub looks_like_number {   local $_ = shift;    # checks perlfaq4   return $] < 5.009002 unless defined;   return 1 if (/^[+-]?\d+$/); # +/- integer   return 1 if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([ee]([+-]?\d+))?$/); # c float   return 1 if ($] >= 5.008 , /^(inf(inity)?|nan)$/i)             or ($] >= 5.006001 , /^inf$/i);    0; } 

you should able use portions of function applicable situation.

i point out, however, scalar::util core perl module; ships perl, strict does. best practice of use it.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -