In Perl - can short circuit evaluation be disabled if necessary?

This is the next question for this .

For example, let's say I have three procedures that I need to start no matter what happens if they all return 1.

while (&proc1 && &proc2 && &proc3); 

Since Perl uses a short circuit rating, the code may or may not execute subs & proc2 and & proc3 depending on previous operands (if the operand is false, the following operands will not execute; href = "http://www.perlmonks.org/? node_id = 301355 "rel =" nofollow noreferrer "> here and in the wiki ). If necessary, is there a way to disable this feature?

+2
source share
4 answers

You can use the multiplication operator

 while (&proc1 * &proc2 * &proc3) { ... } 

This will evaluate all three operands and evaluate to false if any of them is false (zero).

If you are worried about warnings about uninitialized values, you can use bitwise - and with !! discarding to a boolean pseudo-operator:

 while (!!&proc1 & !!&proc2 & !!&proc3) { ... } 

which will do almost the same thing. Boolean casting is necessary because the result of bitwise and two arbitrary true values ​​can still be false (for example, 1 & 2 evaluates to 0 ).

+3
source

You can simply evaluate each sentence for temporary variables, and then evaluate the entire expression. For example, to avoid evaluating a short circuit in:

 if ($x < 10 and $y < 100) { do_something(); } 

records:

 $first_requirement = ($x < 10); $second_requirement = ($y < 100); if ($first_requirement and $second_requirement) { do_something(); } 

Both conditions will be evaluated. Presumably, you need more complex conditions with side effects, otherwise there is no reason to evaluate the second condition if the first is false.

+8
source

You can write

 until ( grep !$_, proc1(), proc2(), proc3() ) { ... } 

No matter what you do, you should not call routines using ampersand syntax, such as &proc1 . This has been wrong for many years, replaced by proc1()

+5
source

I don’t know how to disable short circuit assessment, but you can evaluate each component at the beginning of the loop body and break if any of the conditions is false.

 while (1) { my $result1 = &proc1; my $result2 = &proc2; my $result3 = &proc3; last unless ($result1 && $result2 && $result3); ... } 
+1
source

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


All Articles