Muddled numbers & strings

Perl's ambiguous scalars behaving badly

A funny thing happened again, serialising XML data into JSON with JSON::Create. The gist of it looks like this:

my @funky = ("8.5", "9", "10.5");
for (@funky) {
    $_ = int ($_);
my $funkyjson = create_json (\@funky);

The outcome of this is


So where it has changed a floating point number into an integer from a string, we get quotes around the number, but otherwise we don’t get the quotes. I’m not sure if this is the fault of Perl or of my module.

Internally Perl calls these things names like SvPV, SvPVNV, SvPVIV and so on. There is something called Perlguts illustrated which shows you all the parts, with diagrams:

I’m not entirely sure where my string -> floating point -> integer numbers live on this hierarchy, or why they got these arbitrary-seeming quotes around them.

One hour later…

It turned out that I’d made an elementary blunder. When dealing with SvPVNV in the above, which is a “string plus floating point number”, the test SvNOK tests if the scalar contains a valid floating point number, but this actually fails if it contains an integer. One has to test with SvNIOK, where N is number (double) and I is integer, then test separately for SvNOK and SvIOK after that.

For full details, see this commit.