Is Perl optimized to skip the remaining logical operands if the answer is already resolved?

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

 if (($do eq 'b') && (/text/)) { do stuff } 

Will perl evaluate the first bracket and the second bracket regardless of whether it stops when evaluating the second bracket if the first bracket was false?

The next question is here . (I did not know if I should ask a new question or post it here)

+4
source share
6 answers

Yes. This behavior is commonly used in idiomatic perl.

Consider:

 open FILE, ">$fname" or die $!; 

If there is no error opening the file ( open returns true), the die statement is not executed. This is not a special approach to die ; this is exactly how perl handles logical evaluation.

+7
source

Yes, Perl closes logical operators. This means that they can be used for control flow:

 say "foo" if $bar; 

coincides with

 $bar and say "foo"; 

and

 if ($cond) { stuff() } 

coincides with

 $cond and do { stuff() } 

However, the entire if condition must be wrapped in parens, creating your example

 if ($do eq 'b' && /text/) { do stuff; } 

( && same as and , but has a higher priority)

+4
source

Short answer: it stops (“short circuits” as indicated by AJ). You can get more tons here .

+4
source

Yes. This behavior is called short-circuited in the perlop documentation (highlighted by me).

C-style logic and

Binary && performs a logical short circuit operation. That is, if the left operand is false, the right operand is not even evaluated. A scalar or list context extends to the right operand, if evaluated.

Logical style C or

Binary || Performs a logical OR short circuit operation. That is, if the left operand is true, the right operand is not even evaluated. A scalar or list context extends to the right operand, if evaluated.

In addition to && and || their younger relatives with higher priority and and or also have a short circuit.

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

+4
source

It will be

 if ($do eq 'b' && /text/) { do stuff } 

Yes - if $do eq 'b' is false, /text/ will not be evaluated.

+2
source

No, the right side of the condition is not evaluated if the left side is false ,

 if ($do eq 'b' && /text/) { do stuff } 
+2
source

Source: https://habr.com/ru/post/1486925/


All Articles