Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

How to check Inputs if Numeric

by kasmot (Novice)
on Mar 31, 2004 at 09:54 UTC ( #341265=perlquestion: print w/replies, xml ) Need Help??
kasmot has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Im new in Perl Im just wondering if theres a function of command in Perl to check if the inputted data is a numeric. I mean like the isnum or isdigit in C.

Replies are listed 'Best First'.
Re: How to check Inputs if Numeric
by Tomte (Priest) on Mar 31, 2004 at 10:00 UTC

    you could use Scalar::Utils looks_like_number:

    use Scalar::Util qw(looks_like_number); my $myval = someKindOfUserInput(); # jepp, I'm mostly into java here @ +work ,) [...] if (looks_like_number($myval)) { # a number, maybe even Inf or somesuch thing } [...]
    Edit: "enhanced" the code-snippet, declaring the tested variable...


    Hlade's Law:

    If you have a difficult task, give it to a lazy person --
    they will find an easier way to do it.

      To check if a variable is a positive integer, do you recommend to use Scalar::Util::LooksLikeNumber or one of the suggested simple code without installing a new module could be used?

        This question was actually from me. Something went wrong with my login and my login was not recorded.

Re: How to check Inputs if Numeric
by Abigail-II (Bishop) on Mar 31, 2004 at 11:22 UTC
    Hmmm, isdigit in C works on characters, not strings. Is that what you mean? In that case, you could do:
    $input =~ /^[[:digit:]]$/
    But if you want to know whether a string is "numeric", take a look at Regexp::Common, which has a bunch of regexes to determine whether a string contains a "number" - depending on what kind of number you are looking for (integer, signed integers, decimal numbers, floats, different bases, group separators, etc).


Re: How to check Inputs if Numeric
by pelagic (Priest) on Mar 31, 2004 at 10:04 UTC
    Here is a possibility. It checks whether anything in your input contains something else than digits or decimal point.
    It fails with strings like '....' or '1.2.333.44..55' :
    #!/usr/bin/perl -l use strict; my @inputs = ( qw[1 2 878787 777s7 3.4 3,4 77 abcdef ABCSDEF :: איט !! +!?]); foreach (@inputs) { if ( m/[^0-9.]/ ) {print "$_ \tis not numeric";} else {print "$_ \tis numeric";} } __OUTPUT__ 1 is numeric 2 is numeric 878787 is numeric 777s7 is not numeric 3.4 is numeric 3,4 is not numeric 77 is numeric abcdef is not numeric ABCSDEF is not numeric :: is not numeric איט is not numeric !!!? is not numeric __END__

    I can resist anything but temptation.

      Yours fails for negative numbers, and for strings with more than one decimal place

      It's not easy to juggle a pregnant wife and a troubled child, but somehow I managed to fit in eight hours of TV a day.
        > Yours fails for negative numbers
        I know it's primitive. But I coded it in about 5 seconds and for some application it might be good enough.

        > , and for strings with more than one decimal place
        Not True. It declares anything containing something else than numbers and decimal ponit(s) as non-numeric.

        For a real application I'd use something like Abigail's Regexp::Common

        I can resist anything but temptation.
Re: How to check Inputs if Numeric
by Hena (Friar) on Mar 31, 2004 at 10:23 UTC
    Isdigit would be easy.
    Any number is harder. Heres what i have around on it.
    But i'm reasonably sure there is some modules in CPAN for this.
Re: How to check Inputs if Numeric
by zentara (Archbishop) on Mar 31, 2004 at 15:14 UTC
    Here is something I picked up here awhile ago:
    #!/usr/bin/perl print is_numeric(10),"\n"; print is_numeric('3rd'),"\n"; print is_numeric("NA"),"\n"; print is_numeric(2.34),"\n"; print is_numeric(0.234+E06),"\n"; sub is_numeric { no warnings; use warnings FATAL => 'numeric'; return defined eval { $_[ 0] == 0 }; }

    I'm not really a human, but I play one on earth. flash japh
Re: How to check Inputs if Numeric
by bronto (Priest) on Mar 31, 2004 at 18:39 UTC

    That's an FAQ actually, as you can find browsing the output of perldoc -q number:

    How do I determine whether a scalar is a number/whole/integer/f +loat? + Assuming that you don't care about IEEE notations like "NaN" or + "Infin- ity", you probably just want to use a regular expression. + 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 num +ber\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 funct +ion "looks_like_number" for determining whether a variable looks li +ke a number. Data::Types exports functions that validate data types + using both the above and other regular expressions. Thirdly, there is + "Reg- exp::Common" which has regular expressions to match various typ +es of numbers. Those three modules are available from the CPAN. + If you're on a POSIX system, Perl supports the "POSIX::strtod" +func- tion. Its semantics are somewhat cumbersome, so here's a "getn +um" wrapper function for more convenient access. This function tak +es a string and returns the number it found, or "undef" for input th +at isn't a C float. The "is_numeric" function is a front end to "getnum +" if you just want to say, ``Is this a float?'' + sub getnum { use POSIX qw(strtod); my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) } Or you could check out the String::Scanf module on the CPAN ins +tead. The POSIX module (part of the standard Perl distribution) provi +des the "strtod" and "strtol" for converting strings to double and long +s, respectively.

    I had your same problem, too :-)


    The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
    --John M. Dlugosz
      Thanks to all. You guys here were really very good and of great help.. More Power..

        I know this thread is old but it came up on google firstish. I searched, then came up with my own line, which I think works better than the regexp. I did not check all over, so most likely it is already around somewhere.

        if ( $input+0 eq $input ){ print "it is a number!\n";}

        Can someone point out the problem with this approach? Advantage for me: easy + quick, no problems with signs...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://341265]
Approved by broquaint
Front-paged by grinder
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2018-06-23 00:02 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.