in reply to String to Integer, for json file

JSON is more strongly typed than Perl. Perl (the language) is designed to not really make a strong distinction between an integer and a string. But internally there is a distinction. The "SV" entity that comprises a Perl scalar variable may have an "IV" (integer value) stored in it, or a "PV" (pointer to a string), or both (as well as a few other things). Perl mostly silently vivifies PV's and IV's within scalars as needed. So if you start with $var = 100;, that scalar variable holds just an IV. Now if you say print "$var\n";, $var goes through a stringification process that results in a PV being created within the scalar too. This is all taking place hidden behind the black box of Perl's internals, and in most circumstances this implementation detail is not relevant or even noticed.

However, JSON is typed, and JSON encoders have to decide whether a scalar contains an integer or a string. Most of the time the way they decide is by looking inside the variable to see if there is a PV. Remember, scalars may contain both. But the existence of an IV is overruled by the existence of a PV.

So you have to be very careful that this variable you're encoding has never been treated as a string. Or that a new variable is used: my $new_var = 0 + $var;.


Dave

Replies are listed 'Best First'.
Re^2: String to Integer, for json file
by tangent (Parson) on Dec 12, 2013 at 09:38 UTC
    Thank you davido for the explanation, it has truly enlightened me.
      A string can become a number again :) Its the flags that reveal the true nature (last touch)
      use JSON qw/ to_json from_json /;
      use Devel::Peek qw/ Dump /;
      my $q = 3;
      print "$q\n";
      Dump( $q );
      $q++;
      Dump( $q );
      print to_json( { a => 3, qw/ b 3 q/, $q } );
      __END__
      3
      SV = PVIV(0x9a3778) at 0x99b524
        REFCNT = 1
        FLAGS = (PADMY,IOK,POK,pIOK,pPOK)
        IV = 3
        PV = 0xad23fc "3"\0
        CUR = 1
        LEN = 12
      SV = PVIV(0x9a3778) at 0x99b524
        REFCNT = 1
        FLAGS = (PADMY,IOK,pIOK)
        IV = 4
        PV = 0xad23fc "3"\0
        CUR = 1
        LEN = 12
      {"a":3,"q":4,"b":"3"}
      http://search.cpan.org/dist/illguts/index.html
Re^2: String to Integer, for json file
by halecommarachel (Sexton) on Dec 12, 2013 at 16:38 UTC

    Thank you, davido. This is a very useful explanation. I tried creating a new variable and then storing it in the hash, but I'm still seeing the string in the json file.