Perl三元条件运算符问题中的赋值 [英] Assignment inside Perl ternary conditional operator problems

查看:112
本文介绍了Perl三元条件运算符问题中的赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序中的这段Perl代码给出了错误的结果.

This snippet of Perl code in my program is giving the wrong result.

$condition ? $a = 2 : $a = 3 ;
print $a;

无论$condition的值是多少,输出始终为3,为什么?

No matter what the value of $condition is, the output is always 3, how come?

推荐答案

这在Perl 由于Perl运算符的优先级,该语句被解析为

Because of Perl operator precedence the statement is being parsed as

($condition ? $a= 2 : $a ) = 3 ;

由于?:运算符会产生可分配的结果,因此将3分配给条件的结果.

Because the ?: operator produces an assignable result, 3 is assigned to the result of the condition.

当$ condition为true时,这意味着($ a = 2)= 3给出$ a = 3

When $condition is true this means ($a=2)=3 giving $a=3

当$ condition为假时,这意味着($ a)= 3给出$ a = 3

When $condition is false this means ($a)=3 giving $a=3

正确的写法是

$a = ( $condition ? 2 : 3 );
print $a;

我们在工作中被这个问题咬了,所以我在这里发布,希望其他人会发现它有用.

We got bitten by this at work, so I am posting here hoping others will find it useful.

这篇关于Perl三元条件运算符问题中的赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆