How to determine if a variable is numeric in Perl?

Possible duplicate:
How do I know if a variable has a numerical value in Perl?

I want to decide whether a variable (a value parsed from a string) is a number or not. How can i do this? Well, I think it /^[0-9]+$/will work, but is there a more elegant version?

+6
source share
3 answers
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 here: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Perl

+20
source

looks_like_number() Scalar::Util .
. perlfaq: , ///?

+24

Using regular expressions, it is useful to use:

sub is_int { 
    $str = $_[0]; 
    #trim whitespace both sides
    $str =~ s/^\s+|\s+$//g;          

    #flatten to string and match dash or plus and one or more digits
    if ($str =~ /^(\-|\+)?\d+?$/) {
        print "yes  " . $_[0] . "\n";
    }
    else{
        print "no   " . $_[0] . "\n";
    }
}
is_int(-12345678901234);     #yes
is_int(-1);                  #yes
is_int(23.);                 #yes
is_int(-23.);                #yes
is_int(0);                   #yes
is_int(+1);                  #yes
is_int(12345678901234);      #yes
is_int("\t23");              #yes
is_int("23\t");              #yes
is_int("08");                #yes
is_int("-12345678901234");   #yes
is_int("-1");                #yes
is_int("0");                 #yes
is_int("+1");                #yes
is_int("123456789012345");   #yes
is_int("-");                 #no
is_int("+");                 #no 
is_int("yadz");              #no
is_int("");                  #no
is_int(undef);               #no
is_int("- 5");               #no
is_int("+ -5");              #no
is_int("23.1234");           #no
is_int("23.");               #no
is_int("--1");               #no
is_int("++1");               #no
is_int(" 23.5 ");            #no
is_int(".5");                #no
is_int(",5");                #no
is_int("%5");                #no
is_int("5%");                #no

Alternatively, you can use POSIX.

use POSIX;

if (isdigit($var)) {
    // integer
}
+8
source

Source: https://habr.com/ru/post/1766758/


All Articles