In this fourth part of a nine-part article series on the variety of control structures Perl programmers can use, we'll take a close look at logical operators. It is excerpted from chapter three of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).
Logical Operators
We also saw in Chapter 2 that we can join together several tests into one by the use of the logical operators. Table 3-3 provides a summary of those.
Table 3-3. Logical Operators
Operator
Description
$x and $y
True if both $x and $y are true
$x && $y
$x or $y
True if either of $x or $y, or both are true
$x || $y
not $x
True if $x is not true
! $x
The operatorsand,or, andnotare usually used instead of&&,||, and!mainly due to their readability. The operatornot means not, after all. Don’t forget there is a difference in precedence between the two—and,or, andnotall have lower precedence than their symbolic representations.
Multiple Choice: if . . . else
Consider these two if statements:
if ($password eq $guess) { print "Pass, friend.\n"; } if ($password ne $guess) { die "Go away, imposter!\n"; }
We know that if the first test condition is true, then the second one will not be—we’re asking exactly opposite questions: Are these the same? Are they not the same?
In which case, it seems wasteful to do two tests. It’d be much nicer to be able to say, “If the strings are the same, do this. Otherwise, do that.” And in fact we can do exactly that, although the keyword is not otherwise but else:
if ($password eq $guess) { print "Pass, friend.\n"; } else { die "Go away, imposter!\n"; }
That’s
if ( condition ) { action } else { alternative action }
Like theifstatement, those curly braces are required in theelsepart.