7.3. Boolean Operators

Sometimes it is useful to check for the validation of more than one condition. For doing this, Perl supplies boolean operators.

&&

$a && $b evaluates to true if both $a and $b are true. It is called the logical and of the two operands $a and $b.

||

$a || $b (called the logical or of $a and $b) is evaluated to true if one or both of its operands are true.

!

! $a (pronounced "not $a") evaluates to true if $a is false.

Note that if the first operand is evaluated to false in an && operation, the second operand will not be evaluated at all. Similarly, if the first operand of || was found to be true, the second one will not be evaluated either.

If you wish both operands to be evaluated at all times you need to assign them to variables first.

Here are some examples:

print "Please enter the lower bound of the range:\n";
$lower = <>;
chomp($lower);
print "Please enter the upper bound of the range:\n";
$upper = <>;
chomp($upper);
if ($lower > $upper)
{
    print "This is not a valid range!\n";
}
else
{
    print "Please enter a number:\n";
    $number = <>;
    chomp($number);
    if (($lower <= $number) && ($number <= $upper))
    {
        print "The number is in the range!\n";
    }
    else
    {
        print "The number is not in the range!\n";
    }
}

print "Please enter your name:\n";
$name = <>;
chomp($name);
$fl = lc(substr($name, 0, 1));
if (($fl eq "a")||($fl eq "b")||($fl eq "c"))
{
    print "Your name starts with one of the " .
        "first three letters of the ABC.\n";
}
else
{
    print "Your name does not start with one of the " .
        "first three letters of the ABC.\n";
}

Note: The function lc() converts a string to lowercase.


Written by Shlomi Fish