[Purdue-pm] TIL
Mark Senn
mark at purdue.edu
Thu Dec 19 23:09:27 PST 2019
Dave Jacoby <jacoby.david at gmail.com> wrote on 2019-12-18 at 18:53+00:
> use JSON;
> use PerlX::Maybe qw{ maybe provided };
>
> my $json = JSON->new->canonical;
>
> for my $i ( 1 .. 5 ) {
> my $x;
> $x = 1 if int rand 2;
> my $data = { maybe x1 => $x, x2 => $x, provided $i > 3, i => $i, };
> say $json->encode($data);
> }
>
> $ ./maybe.pl
> {"x1":1,"x2":1}
> {"x1":1,"x2":1}
> {"x2":null}
> {"i":4,"x1":1,"x2":1}
> {"i":5,"x2":null}
>
> x1 will always be a thing, but the value will be undefined half the time.
>
> x2 will not be assigned unless the value it it defined exists. we get this
> from `maybe`.
>
> This is roughly
>
> if ( defined $x ) { $data->{x2} = $x }
>
> but so much more concise.
>
> `provided` gives us conditionals.
>
> if ( $i > 3 ) { $data->{$i} = $i }
>
> becomes
>
> provided $i > $3 , i => $i
>
> it's small, among the smallest things thrown at me recently, but if nothing
> else, it makes a smaller JSON string when used.
Here is how I would do this in Raku. -mark
#
# From "The JSON Data Interchange Syntax", second edition, December 2017,
# retrieved from
# http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf
# on 2019-12-20 at 06:31+00:
# A JSON value can be an object, array,
# number, string, true, false, or null.
# There is no "undefined" in JSON so it is my understanding is that a
# name that is not set (i.e., is not in a JSON file) is the same as
# setting that name to "null".
#
# I'd do the above using the following code in Raku (formerly known
# as Perl 6).
#
# Use version 6.d of the Raku language specification.
# This will cause Perl 5 to complain if you try to use
# Perl 5 to run this program.
use v6.d;
use JSON::Class;
class Triple does JSON::Class
{
has Int $.i is rw;
has Int $.x1 is rw;
has Int $.x2 is rw;
}
for 1..5 -> $i
{
$_ = Triple.new();
($i > 3) and $_.i = $i;
(Bool.pick) and $_.x1 = $_.x2 = 1;
# This program doesn't set names to "null" but if it
# did the ":skip-null" below would not print them out.
say $_.to-json():skip-null;
}
More information about the Purdue-pm
mailing list