Forum archive 2000-2006

Michael Gage - Checking whether a string is a number

Michael Gage - Checking whether a string is a number

by Arnold Pizer -
Number of replies: 0
inactiveTopicChecking whether a string is a number topic started 1/25/2001; 9:05:16 AM
last post 1/25/2001; 9:05:16 AM
userMichael Gage - Checking whether a string is a number  blueArrow
1/25/2001; 9:05:16 AM (reads: 992, responses: 0)
I found this prescription for determining whether a string contains a valid number at

Since this often comes up, I've posted it here for future reference:

A scalar value is interpreted as TRUE in the Boolean sense if it is not the null string or the number 0 (or its string equivalent, "0"). The Boolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed.

There are actually two varieties of null strings (sometimes referred to as "empty" strings), a defined one and an undefined one. The defined version is just a string of length zero, such as "". The undefined version is the value that indicates that there is no real value for something, such as when there was an error, or at end of file, or when you refer to an uninitialized variable or element of an array or hash. Although in early versions of Perl, an undefined scalar could become defined when first used in a place expecting a defined value, this no longer happens except for rare cases of autovivification as explained in You can use the defined() operator to determine whether a scalar value is defined (this has no meaning on arrays or hashes), and the undef() operator to produce an undefined value.

To find out whether a given string is a valid non-zero number, it's sometimes enough to test it against both numeric 0 and also lexical "0" (although this will cause -w noises). That's because strings that aren't numbers count as 0, just as they do in awk:

if ($str == 0 && $str ne "0") {
warn "That doesn't look like a number";
That method may be best because otherwise you won't treat IEEE notations like NaN or Infinity properly. At other times, you might prefer to determine whether string data can be used numerically by calling the POSIX::strtod() function or by inspecting your string with a regular expression (as documented in

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+))?$/;

<| Post or View Comments |>