Possible Duplicate:
How do I tell if a variable has a numeric value in Perl?
I want to decide if a variable (value parsed from a string) is a number or not. How can I do that? Well, I guess /^[0-9]+$/
would work, but is there a more elegant version?
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.
let b = s. chars(). all(char::is_numeric);
Perl integers Integers are whole numbers that have no digits after the decimal points i.e 10 , -20 or 100 .
Perl | length() Function length() function in Perl finds length (number of characters) of a given string, or $_ if not specified. Return: Returns the size of the string.
You can use the looks_like_number()
function from the core Scalar::Util module.
See also the question in perlfaq: 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" }
taken from here: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Perl
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