Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Perl's ( or, and ) and ( ||, && ) short-circuit operators?

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?

like image 645
mob Avatar asked Oct 03 '09 01:10

mob


People also ask

What does || mean in Perl?

$a || $b performs logical OR of two variables or expressions. The logical || operator checks either a variable or expression is true.

Are && and || the same?

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

What is the difference between || and or in PHP?

The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.

What is the difference && and || explain with the help of example code?

&& 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.


1 Answers

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

like image 85
Igor ostrovsky Avatar answered Oct 02 '22 21:10

Igor ostrovsky