March 2013 Archives

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"]

About rlauer

user-pic I blog about Perl.