<div dir="ltr"><br>use JSON;<br>use PerlX::Maybe qw{ maybe provided };<br><br>my $json = JSON->new->canonical;<br><br>for my $i ( 1 .. 5 ) {<br>    my $x;<br>    $x = 1 if int rand 2;<br>    my $data = { maybe x1 => $x, x2 => $x, provided $i > 3, i => $i, };<br>    say $json->encode($data);<br>}<br><br><div>$ ./<a href="http://maybe.pl">maybe.pl</a> <br>{"x1":1,"x2":1}<br>{"x1":1,"x2":1}<br>{"x2":null}<br>{"i":4,"x1":1,"x2":1}<br>{"i":5,"x2":null}</div><div><br></div><div>x1 will always be a thing, but the value will be undefined half the time.</div><div><br></div><div>x2 will not be assigned unless the value it it defined exists. we get this from `maybe`.</div><div><br></div><div>This is roughly <br></div><div><br></div><div>if ( defined $x ) { $data->{x2} = $x }</div><div><br></div><div>but so much more concise.<br></div><div><br></div><div>`provided` gives us conditionals.</div><div><br></div><div>if ( $i > 3 ) { $data->{$i} = $i }</div><div><br></div><div>becomes <br></div><div><br></div><div>provided $i > $3 , i => $i<br></div><div><br></div><div>it's small, among the smallest things thrown at me recently, but if nothing else, it makes a smaller JSON string when used.<br></div><div><br></div>-- <br><div dir="ltr" class="gmail_signature" data-smartmail="gmail_signature"><div dir="ltr"><div><div dir="ltr">Dave Jacoby<br>
<a href="mailto:jacoby.david@gmail.com" target="_blank">jacoby.david@gmail.com</a><br>
<br>I deal with my software the way I treat my eldritch abomination: <br> It's not human, it's not even alive in the natural sense. </div><div dir="ltr"> It's nightmare-born and nightmare-shaped, and nightmares don't die easy.<br>  -- @yenzie</div></div></div></div></div>