Is Perl optimized to skip remaining logic operands if the answer is already decided?

后端 未结 6 1760
悲&欢浪女
悲&欢浪女 2020-12-21 04:22

For instance, I need to match some text if $do eq \'b\'. If I run this code:

if (($do eq \'b\') && (/text/))
{
do stuff
}
6条回答
  •  一整个雨季
    2020-12-21 04:52

    Yes. This behavior is called short-circuiting in the perlop documentation (emphasis added).

    C-style Logical And

    Binary && performs a short-circuit logical AND operation. That is, if the left operand is false, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

    C-style Logical Or

    Binary || performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

    In addition to && and || their lower-precedence cousins and and or also short-circuit.

    Perl has an xor operator, but it cannot short-circuit due to the definition of exclusive-or.

提交回复
热议问题