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)
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With