Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Would perl evaluate the first parenthesis and second parenthesis no matter what or would it stop at the evaluation of the second parenthesis if the first parenthesis was false?

Follow-up question here. (I didn't know if I should make a new question or post it here)

like image 233
Anand Wu Avatar asked Nov 29 '22 15:11

Anand Wu


2 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 special treatment of the die routine; it is just the way perl handles logic evaluation.

like image 119
Drew Shafer Avatar answered Dec 11 '22 10:12

Drew Shafer


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

say "foo" if $bar;

is the same as

$bar and say "foo";

and

if ($cond) { stuff() }

is the same as

$cond and do { stuff() }

However, the whole condition of an if has to be wrapped in parens, making your example

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

(&& is the same as and, but has higher precedence)

like image 28
amon Avatar answered Dec 11 '22 10:12

amon