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

18,643

Solution 1

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.

Solution 2

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

Solution 3

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

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

Share:
18,643

Related videos on Youtube

Gordon
Author by

Gordon

Updated on June 04, 2022

Comments

  • Gordon
    Gordon over 1 year

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

  • Ven'Tatsu
    Ven'Tatsu over 12 years
    Your isa_number thinks '0' isn't a number.

Related