How to send boolean value from perl script without converting them into string

boolean, json, perl

Solution

Using `true` and `false` directly in Perl is a syntax error under `use strict` because barewords are then not allowed.

I guess you are using JSON or JSON::XS. Those use scalar references to indicate `TRUE` and `FALSE`. Specifically, `\1` and `\0`.

$data = ( input1 => \1 );

Here's the relevant doc from JSON::XS, which allows Types::Serializer::True and Types::Serializer::False as well:

These special values from the Types::Serialiser module become JSON true and JSON false values, respectively. You can also use `\1` and `\0` directly if you want.

And the doc from JSON, where `JSON::true` and `JSON::false` can also be used:

These special values become JSON true and JSON false values, respectively. You can also use `\1` and `\0` directly if you want.

If you insist on using `true` without quotes as in `my $foo = true`, you could make subs or constants (which are really subs) that return `\1` and `\0`.

use constant false => \0;
sub true () { return \1 } # note the empty prototype

$data = ( input1 => true, input2 => false );

As Sinan points out in his comment, it's faster to use a constant, unless you include an empty prototype (the `()` in the sub definition), because that way Perl can inline the call.

But in my opinion that is less clear than simply using the references. Always think about the next guy working on this code.

Problem

I pass a Perl data structure to `encode_json`, and use its returned value as a input to post to restful API. Example: ``` $data = (input1 => true); $json_data = encode_json($data); print $json_data; // Prints: ["input1":"true"] $url= http://api.example.com/resources/getDataAPI $headers = {Accept => 'application/json', Authorization => 'Basic ' . encode_base64($username . ':' . $password)}; $client = REST::Client->new(); $client->POST($url,($json_data,$headers)); ``` This was working all fine. Recently another developer made few input parameter validations checks, and REST strictly accepts Boolean value, without quotes. I need now to send my input as ``` $data = '["inout1":true]' $client = REST::Client->new(); $client->POST($url,($data,$headers)); ``` All my scripts are failing as input data is encoded into JSON format using `encode_json` function. I can form a JSON data manually, but the input data would be sometimes very huge. Can not identify them and modify ever time. Is there any way I can achieve passing Boolean value without quotation marks?

Original source