Is there a unique method to determine if a variable value is a number, Since the values could be in scientific notation as well (for example, 5.814e-10)?
Use Scalar::Util::looks_like_number() which uses the internal Perl C API's looks_like_number() function, which is probably the most efficient way to do this. Note that the strings "inf" and "infinity" are treated as numbers.
In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.
$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.
The core module Scalar::Util
exports looks_like_number()
, which gives access to the underlying Perl API.
looks_like_number EXPR
Returns true if perl thinks
EXPR
is a number.
From perlfaq4:How do I determine whether a scalar is a number/whole/integer/float?
if (/\D/) { print "has nondigits\n" }
if (/^\d+$/) { print "is a whole number\n" }
if (/^-?\d+$/) { print "is an integer\n" }
if (/^[+-]?\d+$/) { print "is a +/- integer\n" }
if (/^-?\d+\.?\d*$/) { print "is a real number\n" }
if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" }
if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
{ print "a C float\n" }
There are also some commonly used modules for the task.
Scalar::Util
(distributed with 5.8) provides access to perl's internal function looks_like_number
for determining whether a variable looks like a number.
Data::Types
exports functions that validate data types using both the above and other regular expressions.
Thirdly, there is Regexp::Common
which has regular expressions to match various types of numbers.
Those three modules are available from the CPAN
There are also String::Numeric and Regexp::Common::number .. looks handy.
String::Nummeric also has a "a comparison with Scalar::Util::looks_like_number()"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With