http://www.perlmonks.org?node_id=955846

juliosergio has asked for the wisdom of the Perl Monks concerning the following question:

Is there in Perl any function to determine if the contents of a string is numeric?
Something that behaves like:

#! /usr/bin/perl # mytest.pl $s = shift; if (isnumber $s) { print "$s is a number\n"; } else { print "$s isn't a number\n"; }

Then when you call it:

./mytest.pl 123.2 123.2 is a number ./mytest.pl aBcd aBcd isn't a number

Replies are listed 'Best First'.
Re: A function to determine if a string is numeric
by toolic (Bishop) on Feb 24, 2012 at 00:46 UTC
    Scalar::Util::looks_like_number

    This is also a FAQ: perldoc -q number

    use warnings; use strict; use Scalar::Util qw(looks_like_number); my $s = shift; if (looks_like_number($s)) { print "$s is a number\n"; } else { print "$s isn't a number\n"; }

      Hey! Thanks!
      -Sergio

Re: A function to determine if a string is numeric
by ww (Archbishop) on Feb 24, 2012 at 02:28 UTC

    There are many approaches (also asserted by the acronym/phrase "TIMTOWTDI"). Just for fun, here's one of those:

    #!/usr/bin/perl use strict; use warnings; use 5.014; # juliosergio's test.pl print "Enter a number or string: "; my $s = <STDIN>; chomp $s; if ( $s =~ /^[0-9,.E]+$/ ) { # char class, 1 or more of any of th +ose specified say "$s is a number\n"; # & the ^...$ restricts what's teste +d. } else { say "'$s' may be a string\n"; # Not "isn't a number" }

    Execution:

    C:\>numVSstring.pl Enter a number or string: 123.2 123.2 is a number C:\>numVSstring.pl Enter a number or string: 1E3 1E3 is a number C:\>numVSstring.pl Enter a number or string: 17 17 is a number C:\>numVSstring.pl Enter a number or string: now is the time 'now is the time' may be a string C:\>numVSstring.pl Enter a number or string: III 'III' may be a string

    This is not without "gotcha's." *1 The regular expression allows for the decimal digits 0 through 9, for the comma and dot which may be present is oft-encountered numbers, and an E to allow for scientific notation. But one could add and add and not cover all the possibilities withoiut making the regex unable to distinguish between numbers and words like "FIE".

    Another tack one might take involves attempting to use an arithmetic operator on the input string. Perl will try to treat any string as a number as a bit of its DWIMery (and as a language in which variables are not crammed into particular 'types') but a failure to ID an input as a number won't necessarily be more conclusive than this is.

    But, for further self-improvement or just for fun, you may want to to read perlop re 'Unary "-", or use Super Search or Google for "NaN" and "looks_like_number".

    Bottom line: toolic's advice is probably about as good as any you'll find.

    Update: Markup and substituted "digits" for numbers" in the para after the output.

    Update 2 *1 For a knowledgeable discussion of some more of the "gotcha's," see the estimable jwkrahn's reply, below... and ++ that, too.

      $ perl -E' print "Enter a number or string: "; my $s = <STDIN>; chomp $s; if ( $s =~ /^[0-9,.E]+$/ ) { say "$s is a number\n"; } else { say "$s may be a string\n"; } ' Enter a number or string: ,,, ,,, is a number $ perl -E' print "Enter a number or string: "; my $s = <STDIN>; chomp $s; if ( $s =~ /^[0-9,.E]+$/ ) { say "$s is a number\n"; } else { say "$s may be a string\n"; } ' Enter a number or string: EEE EEE is a number $ perl -E' print "Enter a number or string: "; my $s = <STDIN>; chomp $s; if ( $s =~ /^[0-9,.E]+$/ ) { say "$s is a number\n"; } else { say "$s may be a string\n"; } ' Enter a number or string: -777 -777 may be a string

      If you are going to use a regular expression then you should probably read the FAQ: How do I determine whether a scalar is a number/whole/integer/float?

Re: A function to determine if a string is numeric
by trwww (Priest) on Feb 25, 2012 at 06:51 UTC

      use Regexp::Common; use Data::Dumper; use v5.30.0; my $value = "+a1.2cd"; if ( $RE{num}{int} -> matches($value) ) { say "INTEGER patern:\t".$RE{num}{int}; say $value; say "It is Integer"; }elsif ( $RE{num}{real}->matches($value) ) { say "REAL patern:\t".$RE{num}{real}; say $value; say "It is Real"; }else{ say "It is String"; }

      I tried Regexp::Common , but seams to behave weird to me. The code above is saying :

      It is Integer

        That is documented behavior:

        NOT A BUG • The various patterns are not anchored. That is, a pattern like "$RE +{num}{int}" will match against "abc4def", because a substring of the subject ma +tches. This is by design, and not a bug. If you want the pattern to be anc +hored, use something like: my $integer = $RE{num}{int}; $subj =~ /^$integer$/ and print "Matches!\n";

        Enjoy, Have FUN! H.Merijn

        The documentation explains this.

        The various patterns are not anchored. That is, a pattern like $RE {num} {int} will match against "abc4def", because a substring of the subject matches. This is by design, and not a bug. If you want the pattern to be anchored, use something like:
        my $integer = $RE {num} {int}; $subj =~ /^$integer$/ and print "Matches!\n";