Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Perl's logical operators &&, ||, ! take precedence over and, or, and not?

Tags:

perl

This is probably a minor point, but I was wondering why Perl's logical operators (&&, ||, and !) take precedence over the easily understandable "English" logical operators (and, or and not). Is there any advantage of using the former set and any disadvantage of using the latter set in a script?

like image 815
B Chen Avatar asked Mar 04 '13 01:03

B Chen


People also ask

Why do we use logical operators?

The logical operators are used primarily in the expression evaluation to make a decision. These operators allow the evaluation and manipulation of specific bits within the integer. This operator returns true if all relational statements combined with && are true, else it returns false.

What does || do in Perl?

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


2 Answers

If || and or had the same precedence, then

return some_func $test1 || $test2;

would mean

return some_func($test1) || $test2;

instead of

return some_func($test1 || $test2);

or

some_func $test1 or die;

would mean

some_func($test1 or die);

instead of

some_func($test1) or die;

Neither of those changes are desirable.

And while one could debate or is more easily understood than ||, it's harder to read. It's easier to read code when the operators don't look like their operands.

like image 68
ikegami Avatar answered Sep 22 '22 03:09

ikegami


The original &&, || and ! operators are high precedence to match the C language.

The newer (but still old) and, or and not operators were added to simplify some common constructs. For example, compare:

open my $fh, '<', $filename || die "A horrible death!";
open my $fh, '<', $filename or die "A horrible death!";

The first of these is incorrect; the high priority || binds with $filename and die which is not what you want. The second is correct; the low priority or means that the missing parentheses do not lead to ambiguity.

like image 39
Jonathan Leffler Avatar answered Sep 22 '22 03:09

Jonathan Leffler