Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, how to determine if a variable value is a number?

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)?

like image 881
Gordon Avatar asked Mar 11 '11 13:03

Gordon


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 you check if a variable contains a number?

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”.

What is $@ in Perl?

$@ 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.


3 Answers

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.

like image 75
Tim Avatar answered Nov 07 '22 04:11

Tim


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

like image 39
Nikhil Jain Avatar answered Nov 07 '22 05:11

Nikhil Jain


There are also String::Numeric and Regexp::Common::number .. looks handy.

String::Nummeric also has a "a comparison with Scalar::Util::looks_like_number()"

like image 38
Øyvind Skaar Avatar answered Nov 07 '22 03:11

Øyvind Skaar