Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I decide if a variable is numeric in Perl? [duplicate]

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?

like image 568
petersohn Avatar asked Sep 27 '10 12:09

petersohn


People also ask

How do I check if a variable is numeric in Perl?

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.

How do I check if a string contains only numbers in Perl?

let b = s. chars(). all(char::is_numeric);

Is Perl an integer?

Perl integers Integers are whole numbers that have no digits after the decimal points i.e 10 , -20 or 100 .

How do I find the length of a string in Perl?

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.


2 Answers

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?

like image 63
Eugene Yarmash Avatar answered Oct 19 '22 10:10

Eugene Yarmash


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

like image 42
CristiC Avatar answered Oct 19 '22 08:10

CristiC