[caracas-pm] Evaluar null en JSON

Francisco Obispo fobispo at isc.org
Thu Mar 6 21:00:52 PST 2014


On Mar 6, 2014, at 2:24 PM, Alberto Mijares <amijaresp at gmail.com> wrote:

> $ perl -E '$h=[{a=>1,b=>undef},{a=>1,b=>2}]; for (@{$h}) {
> defined($_->{b}) ? $r=$_->{b} : $r=3; say $r;};'
> 
> Yo hubiese esperado obtener
> 
> 3
> 2
> 
> Pero no. Obtuve
> 
> 3
> 3
> 
> ¿Qué opinas?



El problema es el orden en que se evalúan las operaciones:


$  perl -E '$h=[{a=>1,b=>undef},{a=>1,b=>2}]; for (@{$h}) {
defined $_->{b}  ? ($r=$_->{b}) : ($r=3); say $r;};'
3
2



Yo usaría // :

      Perl’s "//" operator is
      related to its C−style or.  In fact, it’s exactly the same as "||",
      except that it tests the left hand side’s definedness instead of its
      truth.  Thus, "$a // $b" is similar to "defined($a) || $b" (except that
      it returns the value of $a rather than the value of "defined($a)") and
      is exactly equivalent to "defined($a) ? $a : $b".  This is very useful
      for providing default values for variables.  If you actually want to
      test if at least one of $a and $b is defined, use "defined($a // $b)”.



$  perl -E '$h=[{a=>1,b=>undef},{a=>1,b=>2}]; for (@{$h}) {
say $_->{b} // 3  };'
3
2






More information about the caracas-pm mailing list