Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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

like image 827
Chad DeShon Avatar asked Jul 11 '09 04:07

Chad DeShon


4 Answers

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]+)?$/
like image 129
cobbal Avatar answered Sep 20 '22 06:09

cobbal


Try Scalar::Util::looks_like_number:

E.g.:

use Scalar::Util qw(looks_like_number);

if (looks_like_number($thingy)) {
    print "looks like $thingy is a number...\n"
}
like image 45
dlowe Avatar answered Sep 20 '22 06:09

dlowe


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.

like image 32
mehmet el kasid Avatar answered Sep 22 '22 06:09

mehmet el kasid


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 )

like image 27
Brad Gilbert Avatar answered Sep 21 '22 06:09

Brad Gilbert