[caracas-pm] Evaluar null en JSON
Alberto Mijares
amijaresp at gmail.com
Thu Mar 6 21:11:40 PST 2014
On Fri, Mar 7, 2014 at 12:30 AM, Francisco Obispo <fobispo at isc.org> wrote:
>
> 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
>
Francisco, muchas gracias. Que casualidad que justo en este momento
estaba leyendo acerca de ese operador en perlop. No lo había usado
nunca y me disponía a ver cómo funciona.
Veo que mi problema era de precedencia. Lo llegué a pensar pero nunca
lo probé. Doble aprendizaje el día de hoy ;-)
Saludos
Alberto Mijares
More information about the caracas-pm
mailing list