perl - 对 'and' 关键字感到困惑

标签 perl

为什么这两段代码会产生不同的输出?

    $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/

相关文章:

perl - 如何通过文件名获取模块名称?

linux - stty : standard input: Inappropriate ioctl for device

perl - 当我处理带有文件句柄的多行字符串时,如何避免 Perl::Critic 警告?

perl - 如何在 Perl 中将多个哈希合并为一个哈希?

MySQL 为新的 "prepare"从服务器断开连接

perl - 观察驼鹿属性的变化

regex - 用正则表达式匹配基于度数的地理坐标

arrays - 如何在 perl 中拆分这个数组?

perl - 从分隔文件中删除列

perl - 如何使用perl添加和替换线阵列中的行