Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl - can a short circuit evaluation be disabled if needed?

This is a follow-up question for this one.

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);

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?

like image 487
Anand Wu Avatar asked Jan 21 '26 18:01

Anand Wu


2 Answers

You could just evaluate every clause to temporary variables, then evaluate the entire expression. For example, to avoid short-circuit evaluation in:

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

write:

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

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

like image 53
Charles Engelke Avatar answered Jan 23 '26 08:01

Charles Engelke


You could write

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

Whatever you do, you shouldn't call subroutines using the ampersand syntax, like &proc1. That has been wrong for many years, replaced by proc1()

like image 40
Borodin Avatar answered Jan 23 '26 08:01

Borodin