When you a need a number

Sometimes you need a number and for whatever reason, someone things you need a string. Try this:

$ cat > foo
#!/usr/bin/perl

use JSON qw/to_json/;
use Scalar::Util qw/looks_like_number/;

my $scalar = shift;

print to_json( [ looks_like_number($scalar) ? $scalar + 0 : $scalar ] ), "\n";
print to_json( [ $scalar ] ), "\n";
^D
$ chmod +x foo.pl
$ ./foo.pl 1.2
[1.2]
["1.2"]

5 Comments

I had to use the trick quite often as our EcmaScript friend is picky about this kind of thing. In my cases I just added 0 though, because I know in advance I've got an integer.

There's JSON::Types to make this sort of thing easy peasy.

looks_like_number is usually fine, until you get a string like "815E12" which probably should not be converted to a number, but it will (that's 815*10^12).

Depends on who you are, I definitely would want that converted to a number!

If it were a "distance" field, yes; if "product_code", probably not.

Leave a comment

About rlauer

user-pic I blog about Perl.