json - Determining if a perl scalar is a string or integer -


from read, perl doesn't have real type integer or string, him $variable scalar.

recently had lot of trouble old script generating json objects required process values inside json must integers, after debug found because simple print function:

json::encode_json

was generating string instead integer, here's example:

use strict;  use warnings;  use json; $score1 = 998; $score2 = 999; print "score1: ".$score1."\n"; %hash_object = ( score1 => $score1, score2 => $score2 ); $json_str = encode_json(\%hash_object);  # work print "$json_str"; 

and outputs:

score1: 998 {"score1":"998","score2":999} 

somehow perl variables have type or @ least how json::encode_json thinks.

is there way find type programmatically , why type changed when making operation concatenation above?

first, incorrect. yes, every values scalar, scalars have separate numeric , string values. that's need know particular question, i'll leave details out.

what need take @ mapping / perl -> json / simple scalars section of documentation json module:

json::xs , json::pp encode undefined scalars json null values, scalars have last been used in string context before encoding json strings, , else number value.

(the docs wrong here. not "last been used in string context" should "was ever used in string context" - once scalar obtains string value won't go away until explicitly write new number it.)

you can force type string stringifying it:

my $x = 3.1; # variable containing number "$x";        # stringified $x .= "";    # another, more awkward way stringify print $x;    # perl you, too, quite 

incidentally comment above why 998 turned string.

you can force type number numifying it:

my $x = "3"; # variable containing string $x += 0;     # numify it, ensuring dumped number $x *= 1;     # same thing, choice yours. 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -