为什么这两段代码会产生不同的输出?
$a = 3;
($a == 4) and print "But I wanted apple, cherry, or blueberry!\n" ;
没有程序输出但是
$a = 3;
print "But I wanted apple, cherry, or blueberry!\n" and ($a == 4);
给:但我想要苹果、樱桃或蓝莓!
最佳答案
因为和
是所谓的"short circuit" operator .这意味着如果您有 condition1 和 condition2
,则会评估第一个条件,并且仅当第一个条件返回 true 时才评估第二个条件。
所以,在
$a = 3;
($a == 4) and print "But I wanted apple, cherry, or blueberry!\n" ;
条件 $a==4
为假,因此不评估 print
语句。
然而,在
$a = 3;
print "But I wanted apple, cherry, or blueberry!\n" and ($a == 4);
print
语句执行它的操作并且 returns true
.评估第二个条件(显然 false
),但打印已经完成。
关于perl - 对 'and' 关键字感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11895172/