Determining if a perl scalar is a string or an integer

From what I read, perl does not have a real type for integer or string, for it, any $ variable is scalar.

I recently had problems with an old script that generated JSON objects required by another process, for which the values ​​inside JSON should be integers, after some debugging, I found that due to a simple print function:

JSON :: encode_json

generated a string instead of an integer, here is my example:

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

And he outputs:

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

Somehow Perl variables are of type, or at least JSON :: encode_json thinks so.

Is there a way to find this type programmatically and why does this type change when performing an operation such as concatenation above?

+4
2

-, . , , . , , .

, MAPPING/PERL → JSON/ JSON module:

JSON:: XS JSON:: PP undefined JSON null , , JSON, .

( . " ", "- " - , , ​​ .)

, :

my $x = 3.1; # some variable containing a number
"$x";        # stringified
$x .= "";    # another, more awkward way to stringify
print $x;    # perl does it for you, too, quite often

, , 998 .

:

my $x = "3"; # some variable containing a string
$x += 0;     # numify it, ensuring it will be dumped as a number
$x *= 1;     # same thing, the choice is yours.
+7

Perl , . JSON, ,

, , . JSON , , , → float-,

, : .

, , Perl , . -

,

use strict;
use warnings 'all';
use feature 'say';

use JSON;

my ($score1, $score2) = (998, 999);

print "score1: $score1\n";

my %data = ( score1 => 0+$score1, score2 => 0+$score2 );

say encode_json(\%data);

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

Source: https://habr.com/ru/post/1627455/


All Articles