Perl - Part 13
[home] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
Logical Operators
Sometimes a program needs to be able to make decisions as to which course of action to take. For this we have the IF..ELSE construct. However, thus far all decisions your programs have made using the IF construct have been based on the value of one variable. Next we shall see how to make a decision based on more than one vairiable, or on a variable having more than one possible value. For this we use logical operators.
The logical operators are AND, OR and NOT:
- AND - both variables or conditions must evaluate to TRUE
- OR - one or other variables or conditions must evaluate to TRUE
- NOT - Logically negate a result: TRUE becomes FALSE and vice versa
An example of the use of the OR operator could come from the last program - in Task 016 - where the program was to keep looping until a value of 'n' was typed. It would be more appropriate to stop the program if either 'n' OR 'N' was typed.
Writing AND, OR, NOT in perl
Some programming languages (such as PASCAL and BASIC) use the actual words AND, OR and NOT. Many other languages, such as C, C++, Perl, Java use symbols instead:
- AND - &&
- OR - ||
- NOT - already seen and used in != and ne
The Catch
AND and OR have operational status the same as +, -, / and *; they can be used for binary mathematical operations. Therefore we have to use them with the same caution as the normal mathematical operators - we must use brackets ('(', ')') to clarify our intent.
Example 1 (AND):
If we have an IF statement with two options that must be true before the body of the structure executes then the general form would be as follows:
if ( ( condition_1 ) && (condition_2) ){
Carry out necessary statements;
}
Example 2 (OR):
If we have an IF statement with two options ANY ONE of which must be true before the body of the structure executes then the general form would be as follows:
if ( ( condition_1 ) || (condition_2) ){
Carry out necessary statements;
}
Create the following program called and01.pl that uses the && function. The program purpose should be reasonably clear.

Task 017
Modify the program responder-xx.pl so that either a large or a small 'n' will stop the program from looping.
Onwards...
[home] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
Last updated: 20120108-16:15