On Wed, May 30, 2001 at 01:56:40PM -0700, [EMAIL PROTECTED] wrote:
> How do I test an input to see if it is a real number?
$ perldoc -q float
Found in /usr/local/lib/perl5/5.6.1/pod/perlfaq4.pod
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.
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 number" }
if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
{ print "a C float" }
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($_[0]) }
Or you could check out the String::Scanf module on CPAN
instead. The POSIX module (part of the standard Perl
distribution) provides the "strtod" and "strtol" for
converting strings to double and longs, respectively.
--
Walter C. Mankowski
Senior Software Engineer Myxa Corporation
phone: (610) 234-2626 fax: (610) 234-2640
email: [EMAIL PROTECTED] http://www.myxa.com