Which of these subroutines is not like the other?
sub or1 { my ($a,$b) = @_; return $a || $b; } sub or2 { my ($a,$b) = @_; $a || $b; } sub or3 { my ($a,$b) = @_; return $a or $b; } sub or4 { my ($a,$b) = @_; $a or $b; }
I came to Perl 5 from C and Perl 4 and always used ||
until I saw more scripts using or
and I liked the way it looked. But as the above quiz shows, it's not without its pitfalls for the unwary. For people who use both constructs or who use a lot of or
, what rules of thumb do you use to decide which construct to use and make sure the code is doing what you think it is doing?
$a || $b performs logical OR of two variables or expressions. The logical || operator checks either a variable or expression is true.
The && and || Operators in JavaScript. If applied to boolean values, the && operator only returns true when both of its operands are true (and false in all other cases), while the || operator only returns false when both of its operands are false (and true in all other cases).
The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.
&& is used to perform and operation means if anyone of the expression/condition evaluates to false whole thing is false. || is used to perform or operation if anyone of the expression/condition evaluates to true whole thing becomes true.
Due to the low precedence of the 'or' operator, or3 parses as follows:
sub or3 { my ($a,$b) = @_; (return $a) or $b; }
The usual advice is to only use the 'or' operator for control flow:
@info = stat($file) or die;
For more discussion, see the perl manual: http://perldoc.perl.org/perlop.html#Logical-or-and-Exclusive-Or
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