
Jasmine
Administrator
Jan 19, 2001, 3:39 PM
Post #1 of 1
(3288 views)
|
How do I determine whether a scalar is a number/wh
|
Can't Post
|
|
(From the Perl FAQ) How do I determine whether a scalar is a number/whole/integer/float? 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 http:// instead. The POSIX module (part of the standard Perl distribution) provides the strtol and strtod for converting strings to double and longs, respectively.
|