Checking Whether a String Is a Valid Number

Problem

You want to check whether a string represents a valid number. This is a common problem when validating input, as in a CGI script.

Solution

Compare it against a regular expression that matches the kinds of numbers you’re interested in.

if ($string =~ /PATTERN/) {
    # is a number
} else {
    # is not
}

Discussion

This problem gets to the heart of what we mean by a number. Even things that sound simple, like integer, make you think hard about what you will accept (“Is a leading + for positive numbers optional, mandatory, or forbidden?”). The many ways that floating-point numbers can be represented could overheat your brain.

You must decide what you will and will not accept. Then, construct a regular expression to match those things alone. Here are some precooked solutions (the cookbook’s equivalent of just-add-water meals) for most common cases.

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

These lines do not catch the IEEE notations of “Infinity” and “NaN”, but unless you’re worried that IEEE committee members will stop by your workplace and beat you over the head with copies of the relevant standards ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.