Using logical operators (&& and ||)
Using logical operators (&& and ||)
-
Control statements can also be modified with a variety of logical operators
that extend the breadth of the control statement truth test using the following
syntax:
[control statement] (([first condition]) [logical operator]
([second condition]))
{
[action to be performed]
}
For example, the "&&" operator can be translated to "and". In usage,
it takes the format used in the following example:
if (($first_name eq "Selena") &&
($last_name eq "Sol"))
{
print "Hello Selena Sol";
}
Translating the logic goes something like this: if the first name is Selena
AND the last name is Sol, then print "Hello Selena Sol". Thus, if $first_name
was equal to "Selena" but $last_name was equal to "Flintstone", the control
statement would test as false and the statement block would not be executed.
Notice that we use parentheses to denote conditions. Perl
evaluates each expression inside the parentheses independently and
then evaluates the results for the entire group of conditions. If either
returns false, the entire test returns false. Parentheses are used to determine
precedence. With more complex comparisons, in which there are multiple
logical operators, the parentheses help to determine the order of evaluation.
Similarly, you may wish to test using the double pipe (||) operator. This
operator is used to denote an "or". Thus, the following code would execute
the statement block if $first_name was Selena OR Gunther.
if (($first_name eq "Selena") ||
($first_name eq "Gunther"))
{
print "Hello humble CGI book author!";
}
Additional Resources:
for
Loops
Table of Contents
Formatting
Control Structures
|