Take the 2-minute tour ×

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)?

share|improve this question

6 Answers 6

up vote 16 down vote accepted

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

share|improve this answer

Try Scalar::Util::looks_like_number:


use Scalar::Util qw(looks_like_number);

if (looks_like_number($thingy)) {
    print "looks like $thingy is a number...\n"
share|improve this answer
just realize that looks_like_number returns true for 'inf', 'nan', '1E02' and probably a few more strings that you might not expect to be numbers. –  mirod Jul 11 '09 at 5:01
why would 1E02 not be a expected to be a number? it's scientific notation for 100. –  Nathan Fellman Sep 11 '09 at 12:30

You could just force it into a number then compare that to the original string.

if( $value eq $value+0 ){
  print "$value is a number\n";

( Note: it will only work for simple numbers, like 123 or 12.3 )

share|improve this answer
Is "0" the same as "0e0" or "0.0" or "-0"? Perl normally thinks so, but your test produces the opposite result. –  jrockway Jul 13 '09 at 3:43

I think (from recent experiences) that you're making a mistake doing any kind of manual XML->JSON conversion. I encountered many gotchas in the process, not least of which involved incorrectly escaped characters.

I would recommend parsing your XML with one of the many XML::* modules (I used XML::Simple) and then rendering it as JSON using JSON::XS. JSON::XS allows you to convert a Perl data structure to JSON; XML::Simple parses XML to a Perl data structure. In the mean time you can manipulate the Perl data structure as you wish.

Bottom line is that you no longer care about quoting/escaping characters.

share|improve this answer

I think this question from perlfaq solves your problem.

Generally the problem is defining what exactly you want to read as number.

  • is "-1.312" valid number?
  • is "inf"?
  • 5.34123412E-03 ?
share|improve this answer

It might be easier for you to just read the XML into a data structure in Perl and let Perl's JSON library figure it out for you. It already has checking for that, so unless your number is actually a string in the XML (e.g. it's got a space after it, etc) JSON->encode() will encode it as a JSON number.

share|improve this answer

Your Answer


