    Next: The Bitwise Operators Up: Operators Previous: The Unary Arithmetic Operators

# The Logical Operators

Logical operators are mainly used to control program flow. Usually, you will find them as part of an if, a while, or some other control statement (Chapter 6)

The Logical operators are:

op1 && op2
-- Performs a logical AND of the two operands.
op1 || op2
-- Performs a logical OR of the two operands.
!op1
-- Performs a logical NOT of the operand.

The concept of logical operators is simple. They allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to a true or false value. Then the value of the conditions is used to determine the overall value of the op1 operator op2 or !op1 grouping. The following examples demonstrate different ways that logical conditions can be used.

The && operator is used to determine whether both operands or conditions are true and.pl.

For example:

```if (\$firstVar == 10 && \$secondVar == 9) {

print("Error!");

};
```

If either of the two conditions is false or incorrect, then the print command is bypassed.

The || operator is used to determine whether either of the conditions is true.

For example:

```if (\$firstVar == 9 || \$firstVar == 10) {

print("Error!");
```

If either of the two conditions is true, then the print command is run.

Caution If the first operand of the || operator evaluates to true, the second operand will not be evaluated. This could be a source of bugs if you are not careful.

For instance, in the following code fragment:

```if (\$firstVar++ || \$secondVar++) { print("\n"); }
```

variable \$secondVar will not be incremented if \$firstVar++ evaluates to true.

The ! operator is used to convert true values to false and false values to true. In other words, it inverts a value. Perl considers any non-zero value to be true-even string values. For example:

```\$firstVar = 10;

\$secondVar = !\$firstVar;

if (\$secondVar == 0) {

print("zero\n");

};
```

is equal to 0- and the program produces the following output:

zero

You could replace the 10 in the first line with "ten," 'ten,' or any non-zero, non-null value.    Next: The Bitwise Operators Up: Operators Previous: The Unary Arithmetic Operators
dave@cs.cf.ac.uk