Previous Table of Contents Next


Session 3
The if Statement and Expressions

Every programming language has some form of the if statement, which allows you to create a conditional statement that might or might not be executed. Until now, every program you’ve seen has executed all of its statements in sequence. That’s okay for simple tasks, but more complicated problems might require the program, say, to print something only if some condition is true and to do nothing otherwise.

Suppose you want a program to ask the user if he or she wants to see a movie. If the user says yes, your program should ask the user for money. In other words,

if (the user types ‘yes’) { ask for money }.

Listing 1-8 features tickets, which shows how you use an if statement.

Listing 1-8 tickets: Using an if statement

#!/usr/bin/perl -w
print ‘Would you like to see the 11:00am showing of Casablanca? ’;
$answer = <>;
chomp $answer;
if ($answer eq ‘yes’) {                         # If the user typed yes,
    print “That’ll be \$8.50, please.\n”;       # ask him for money.
}

There are three new concepts in tickets: the if statement, the eq operator, and the backslashed character \$. We’ll tackle them in that order.


The if Statement
if ( CONDITION ) { BODY } executes BODY if the CONDITION is True.

Some examples of if:

if ($answer eq ‘yes’) { print 20; }

If $answer is equal to yes, then 20 is printed.

if ($answer ne ‘yes’) {
    $answer = ‘maybe’;
}

If $answer is not equal to yes, then $answer is set to maybe.

In tickets, the user is asked for money only if he or she types yes. The CONDITION is ($answer eq ‘yes’) and the BODY consists of a solitary print() statement. When an if statement is used in this way, it requires parentheses around the condition and curly braces around the body (Figure 1-4).


Figure 1-4  An if...else statement

Here’s a different way to use if:

#!/usr/bin/perl
print ‘Would you like to see the 11:00am showing of Cape Fear? ’;
$answer = <>;
chomp $answer;
print “That’ll be \$8.50, please.\n” if $answer eq ‘yes’;

Both programs behave exactly the same because:


Alternate Syntaxes for if

STATEMENT if CONDITION is the same as if (CONDITION) { STATEMENT }.
STATEMENT unless CONDITION executes STATEMENT if CONDITION is false.

As you’d expect,

print ‘Hello’     if     $answer eq ‘yes’;

prints Hello if $answer is equal to yes.

$answer = ‘maybe’ if     $answer ne ‘yes’;

sets $answer to maybe if $answer is not equal to yes,which is the same as saying

$answer = ‘maybe’ unless $answer eq ‘yes’;

Use whichever syntax you wish. That said, it’s often a Good Thing to present readers with the important clause first.

print “Phase 1---Checking Carbon Monoxide levels” if $debug;

if ($sea_levels eq “rising”) { $anxiety += 17; }

are easier to understand than

if ($debug) { print “Phase 1---Checking Carbon Monoxide levels”; }

$anxiety += 17 if $sea_levels eq “rising”;

One of the tenets of Perl is, “There’s always more than one way to do it.” You’ll see this again and again throughout the book.

Expressions

An expression is anything that, when evaluated, yields some value (Figure 1-5). The CONDITION of the if statement ($answer eq ‘yes’) is an expression, as are these.


Figure 1-5  Expressions

4 * 5

evaluates to 20,

$answer

evaluates to the value of $answer, and

chop $answer

evaluates to whatever character was lopped off from $answer.

Every expression yields a particular value—usually a number or a string. The expression 4 * 5 yields 20, as you’d expect. But assignments are expressions, too: $answer = <> yields $answer after <> is assigned to it. That’s why you’ll often see

$answer = <>;
chomp $answer;

written as

chomp($answer = <>);

All values are either TRUE or FALSE. The values shown in Table 1-1, and no others, are FALSE.

Table 1-1 FALSE values

Example Value Description

0 (the number)
(an empty string)
“0” (a string containing just the 0 character)
( ) (an empty array—introduced in Session 5)
Undefined values (all variables that haven’t been assigned values)

All other values are TRUE. Uninitialized variables are set to a FALSE value, so

print “false!” unless $uninitialized_variable;

prints false!, as do

print “false!” unless 0;

and

print “false!” unless “”;

So ($answer eq ‘yes’) will either be TRUE or FALSE, depending on the value returned by the eq operator. eq operates on strings, in this case $answer and ‘yes’, returning TRUE if the strings are equal and FALSE if they’re not. So if $answer is yes, the condition evaluates to TRUE and the print() statement inside the curly braces is executed.

You’ll often see eq used in just this way, as the condition of an if statement.

        % perl -e ‘ if (“yes” eq “yes”) { print “true\n”; } ’
RESULT: true

        % perl -e ‘ if (“yes” eq “no”)  { print “true\n”; } ’

prints nothing.


Previous Table of Contents Next