The Incredible Journey

Share this post
Muddled numbers & strings
benbullock.substack.com

Muddled numbers & strings

Perl's ambiguous scalars behaving badly

Ben Bullock
Apr 28, 2021
Comment
Share

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

["8",9,"10"]

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.

CommentComment
ShareShare

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

TopNew

No posts

Ready for more?

© 2022 Ben Bullock
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing