在Perl中-是否可以根据需要禁用短路评估? [英] In Perl - can a short circuit evaluation be disabled if needed?
问题描述
这是例如,假设我有三个过程,无论执行什么操作都必须运行,如果所有过程都返回1,则退出.
For example, let's say I have three procedures that I need to run no matter what and exit if all of them return 1.
while (&proc1 && &proc2 && &proc3);
由于Perl使用短路评估,因此代码可能会或可能不会执行subs& proc2和& proc3,具体取决于前面的操作数(如果操作数为false,则不会执行以下操作数;更多信息此处和
Because Perl is using short-circuit evaluation, the code may or may not execute subs &proc2 and &proc3 depending on preceding operands (if an operand is false the following operands won't be executed; more info here and on wiki). If needed, is there any way to turn the feature off?
推荐答案
您可以使用乘法运算符
while (&proc1 * &proc2 * &proc3) { ... }
这将对所有三个操作数求值,如果其中任何一个为假(零),则求值为假.
This will evaluate all three operands and evaluate to false if any one of them is false (zero).
如果您担心有关未初始化值的警告,则可以按位-并与!!
强制转换为布尔值的伪运算符一起使用:
If you are worried about warnings about uninitialized values, you can use bitwise-and with the !!
cast-to-boolean pseudo-operator:
while (!!&proc1 & !!&proc2 & !!&proc3) { ... }
将执行几乎相同的操作.强制转换为布尔值是必须的,因为按位和两个任意真实值的结果可能仍为假(例如,1 & 2
的结果为0
).
which will do pretty much the same thing. The cast-to-boolean is necessary because the result of a bitwise-and of two arbitrary true values may still be false (e.g., 1 & 2
evaluates to 0
).
这篇关于在Perl中-是否可以根据需要禁用短路评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!