Your skill will accomplishwhat the force of many cannot PerlMonks

### How do I determine whether a scalar is a number/whole/integer/float?

by faq_monk (Initiate)
 on Oct 08, 1999 at 00:20 UTC Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

Assuming that you don't care about IEEE notations like ``NaN'' or ``Infinity'', you probably just want to use a regular expression.

```   warn "has nondigits"        if     /\D/;
warn "not a natural number" unless /^\d+\$/;             # rejects -3
warn "not an integer"       unless /^-?\d+\$/;           # rejects +3
warn "not an integer"       unless /^[+-]?\d+\$/;
warn "not a decimal number" unless /^-?\d+\.?\d*\$/;  # rejects .2
warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)\$/;
warn "not a C float"
unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\$/;
```

If you're on a POSIX system, Perl's supports the `POSIX::strtod` function. Its semantics are somewhat cumbersome, so here's a `getnum` wrapper function for more convenient access. This function takes a string and returns the number it found, or undef for input that 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 }
```

Or you could check out http://www.perl.com/CPAN/modules/by-module/String/String-Scanf-1.1.tar.gz instead. The POSIX module (part of the standard Perl distribution) provides the `strtol` and `strtod` for converting strings to double and longs, respectively.

Create A New User
Chatterbox?
 [marto]: trench humour folks, feeling rough. [marto]: there is never a night when they sleep all the way through, but last night was something else [marto]: gave in at 3:45 ish and let Charlie watch videos about spitfires, the battle of Britain. He's plane crazy [1nickt]: marto soothing! [marto]: Hiromi makes an appearance, let's hope Jools doesn't ruin it by joining in on the old Joanna [1nickt]: karlgoethebier What is the issue with the semic-colon after the ellipsis? It's documented as proper syntax ...; [karlgoethebier]: Crazy? What should i say? Son just started his third studies. Next week i have a session with my therapist ;-) [marto]: and just as I type that, the boys begin playing the piano, the price I pay for using cockney slang :P

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2017-11-18 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (277 votes). Check out past polls.

Notices?