Search code examples
perl

In Perl, how can I tell if a string is a number?


I am using Perl to convert some XML to JSON. If the XML attribute is a number, I don't want to put quotes around it so that JSON will treat it as a number and not a string. How can I tell if a Perl string is a number (contains only numbers 0 through 9 and possibly one decimal point)?


Solution

  • The JSON specification provides fairly clear rules on the format of a number, so the following regex should work:

    /^-?(0|([1-9][0-9]*))(\.[0-9]+)?([eE][-+]?[0-9]+)?$/