[Purdue-pm] TIL
Dave Jacoby
jacoby.david at gmail.com
Wed Dec 18 10:53:07 PST 2019
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.
--
Dave Jacoby
jacoby.david at gmail.com
I deal with my software the way I treat my eldritch abomination:
It's not human, it's not even alive in the natural sense.
It's nightmare-born and nightmare-shaped, and nightmares don't die easy.
-- @yenzie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.pm.org/pipermail/purdue-pm/attachments/20191218/9fcaf598/attachment-0001.html>
More information about the Purdue-pm
mailing list