CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
How do I determine whether a scalar is a number/wh

 



Jasmine
Administrator

Jan 19, 2001, 3:39 PM

Post #1 of 1 (1866 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.

Code
   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.


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives