Next: Defined and existence
Up: Conditionals
Previous: if/elsif/else and switch statemements
Contents
Index
Multiple conditions
At times you may have more than one condition that
you want satisfied in order to execute a series of
statements. For this you can specify the conditions
as follows:
my $age = 22;
if ($age < 30 && $age > 10) {
print qq{You're young, but no spring chicken\n};
}
In this example, both $age < 30 and $age > 10
must be satisfied in order that the specified statement be
executed. There are also occasions when you want either
one condition or another to be true to carry out some
operation. This can be done as
my $age = 22;
if ($age < 13 || $age > 19) {
print qq{You're not a teenager\n};
}
Here, either $age < 13 or $age > 19 must
be true in order that the specified statements be executed.
If you have multiple such conditions to test for, it is
wise to group them using brackets:
my $age = 22;
my $gender = 'female';
if ($gender eq 'female' && ($age < 13 || $age > 19) ) {
print qq{You're a female, but not a teenager\n};
}
Sometimes, it is more natural to express a condition as
the negation of another condition. For this, you can use
the ! operator:
my $age = 22;
my $gender = 'female';
if ($gender eq 'female' && ! ($age > 12 && $age < 20) ) {
print qq{You're a female, but not a teenager\n};
}
Perl provides an (almost) alternate syntax for the
&&, ||, and ! operators:
- and for &&
- or for ||
- not for !
These are not exact equivalences (differences arise in
how tightly the operators ``bind'' to the expression to
the right of the operator), but for simple purposes
you can use either.
Next: Defined and existence
Up: Conditionals
Previous: if/elsif/else and switch statemements
Contents
Index