Hi Adam,
Thanks for writing this very useful module. However, I found a bug:
The module does not properly deal with scalars like '3Com'.
$value = '3Com';
$value != 0 ---> 1;
This causes the following routine to leave scalars like 3Com to be
returned unquoted.
# Turn a single perl value into a single javascript value
sub anon_scalar {
my $class = shift;
my $value = isa( $_[0], 'SCALAR' ) ? ${shift()} : shift;
return 'null' unless defined $value;
{ no warnings;
if ( $value eq '0' or $value != 0 ) {
return $value;
} else {
$value =~ s/"/\\"/g;
return '"' . $value . '"';
}
}
}
I did a bit of research and it turns out that there is no easy regexp
way of detecting a numeric value (there are a lot of forms: 1.23, -1.23,
1.23e0, 0.23, .23, etc...)
One way to detect a number:
use POSIX qw(strtod);
sub is_numeric ($) {
my ($str) = @_;
return 0 unless defined $str;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
return 0 unless length $str;
$! = 0;
my ($num, $unparsed) = strtod($str);
return 0 if $unparsed != 0 or $!;
return 1;
}
Note that you have the same $value != 0 test in the anon_hash_key
subroutine.
Thanks,
Pasha