develooper Front page | perl.perl5.porters | Postings from February 2022

Re: Pre-RFC: builtin:: functions for detecting numbers vs strings

Thread Previous | Thread Next
Darren Duncan
February 28, 2022 10:15
Re: Pre-RFC: builtin:: functions for detecting numbers vs strings
Message ID:
On 2022-02-28 1:41 a.m., Dan Book wrote:
> On Mon, Feb 28, 2022 at 4:27 AM Tom Molesworth wrote:
>     On Mon, 28 Feb 2022 at 16:56, Dan Book wrote:
>         On Mon, Feb 28, 2022 at 3:27 AM Philippe Bruhat (BooK) wrote:
>             When parsing `{ "a" : 2, "b": "c" }`, all that Perl reads is text. How
>             would a pure Perl JSON parser decode that `2` from the input source and
>             keep it in memory as if it was always the number 2?
>         That's not the case - JSON parsers are aware whether they are parsing a
>         number or a string because the JSON grammar is distinct, and can create
>         the scalar differently depending. Not like e.g. certain databases where
>         you can't always tell the type of the response values.
>         Cpanel::JSON::XS::Type uses this information to return a type schema
>         which you can already use to round-trip the output - these sort of
>         changes enable more opportunities.
>     I think the point here is "how does pure perl say 'this string in $x was
>     always a number'". Extracting the number 2 from a string of JSON is easy
>     enough, presumably `substr` or regex were involved to get to that point -
>     but how do we then set the "this was originally a number" flag to make the
>     roundtrip work? Hopefully something in `builtin` or equivalent will provide
>     that, rather than requiring XS calls to internal APIs!
> I do believe that is the original topic of this thread...

I do believe that the answer to this is that a Perl value produced as the result 
of some kind of operation, such as a string or numeric or boolean or etc is 
brand new as the result of that operation, and so "originally" is defined as 
when that operation produced it.  So when you say "my $x = $y + $z", then $x is 
"originally" a number because "+" produced it.  Or, anything produced by a regex 
is a string because regexes are string operations.  Likewise, "0+$w" produces a 
number so its result is "originally" a number, so do that, or some other 
explicit cast operator like "int $w" etc, with values pulled from JSON to make 
them canonically numbers. -- Darren Duncan

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About