...
Wiki Markup |
---|
Perl also provides three alternatealternative logical operators: {{and}}, {{or}}, and {{not}}. They have the same meanings as {{&&}}, {{||}}, and {{\!}}. They have much lower binding precedence, which makes them useful for control flow \[[Wall 2011|AA. Bibliography#Manpages]\]. They are called the late-precedence logical operators, whereas {{&&}}, {{||}}, and {{!}} are called the early-precedence logical operators. |
It is possible to mix the early-precedence logical operators with the late-precedence logical operators, but this mixture of precedence will often lead leads to confusing, counterintuitive behavior. Therefore, every Perl expression should use either the early-precedence operators or the late-precedence ones, never both.
Wiki Markup |
---|
\[[Conway 2005|AA. Bibliography#Conway 2005]\] recommends avoiding the use of {{not}} and {{and}} entirely, and only using {{or}} only in control-flow operations, as a failure mode: |
...
This noncompliant code example checks a file to see if it is suitable for suitability as an output file. It does this by checking to see that the file does not exist.
...
This code is perfectly fine. However, it is later amended to also work if the file does exist , but can be overwritten.
Code Block | ||||
---|---|---|---|---|
| ||||
if (not -f $file || -w $file) { |
This code will not behave as expected , because the binding rules are lower for the not
operator than for the !
operator. This code will instead behave like the followinginstead behaves as follows:
Code Block | ||
---|---|---|
| ||
if (not (-f $file || -w $file)) { |
...
This compliant solution uses the !
operator in conjunction with the ||
operator. This code has the desired behavior of determining if a file either does not exist , or does exist but is overwritable.
...
This compliant solution uses the early-precedence operators consistently. Again, the code works as expected.
...