Previous Page Next Page

Chapter 7. If Only, Unconditionally, Forever

7.1. Control Structures, Blocks, and Compound Statements

People plan their lives by making decisions, and so do programs. Figure 7.1 is a flow chart. A flow chart is defined as a pictorial representaion of how to plan the stages of a program. It helps you to visualize what decisions need to be made to accomplish a task. According to computer science books, a good language allows you to control the flow of your program in three ways:

Figure 7.1. A flow chart.


So far, we have seen script examples that are linear in structure; that is, simple statements that are executed in sequence, one after the other. Control structures, such as branching and looping statements, allow the flow of the program's control to change depending on some conditional expression.

The decision-making constructs (if, if/else, if/elsif/else, unless, etc.) contain a control expression that determines whether a block of statements will be executed.

The looping constructs (while, until, for, foreach) allow the program to repetitively execute a statement block until some condition is satisfied.

A compound statement, or block, consists of a group of statements surrounded by curly braces. The block is syntactically equivalent to a single statement and usually follows an if, else, while, or for construct. But unlike C, where curly braces are not always required, Perl requires them even with one statement when that statement comes after the if, else, while, etc. The conditional modifiers, discussed in Chapter 8, "Regular Expressions—Pattern Matching," can be used when a condition is evaluated within a single statement.

7.1.1. Decision Making—Conditional Constructs

if and unless Statements

The if and unless constructs are followed by an expression surrounded by parentheses and followed by a block of one more statements. The block is always enclosed in curly braces.

An if statement is a conditional statement. It allows you to test an expression and, based on the results of the test, make a decision. The expression is enclosed in parentheses, and Perl evaluates the expression in a string context. If the string is non-null, the expression is true; if it is null, the expression is false. If the expression is a numeric value, it will be converted to a string and tested. If the expression is evaluated to be true (non-null), the next statement block is executed; if the condition is false (null), Perl will ignore the block associated with the expression and go on to the next executable statement within the script.

The unless statement is constructed exactly the same as the if statement; the results of the test are simply reversed. If the expression is evaluated to be false, the next statement block is executed; if the expression is evaluated to be true, Perl will ignore the block of statements controlled by the expression.

The if Construct

The if statement consists of the keyword if, followed by a conditional expression, followed by a block of one or more statements enclosed in curly braces. Each statement within the block is terminated with a semicolon (;). The block of statements collectively is often called a compound statement. Make sure when you are testing strings that you use the string operators shown in Table 6.7 and that if testing numbers, you use the numeric operators also shown in Table 6.6. Perl converts strings and numbers to conform to what the operator expects, so be careful. A test such as "yes" == "no" is incorrect. It should be "yes" eq "no".

Format

if (Expression) {Block}
if (Expression) {Block} else {Block}
if (Expression) {Block} elsif (Expression)
   {Block}... else {Block}

Example 7.1.

(The Script)
1   print "How old are you? ";
2   chomp($age = <STDIN>);
3   if ($age >= 21 ){  # If true, enter the block
4          print "Let's party!\n";
    }
5   print "You said you were $age.\n";

(Output)
1   How old are you? 32
4   Let's party!
5     You said you were 32.

-------------Run the program again -------------
(Output)
1   How old are you? 10
5   You said you were 10.

Explanation

  1. The user is asked for his age.

  2. The scalar $age is assigned a value.

  3. The scalar $age is tested. If its value is greater than or equal to 21 (i.e., the expression evalutaes to true), then the block is entered and line 4 is executed.

  4. If the user is older than 21, this line is printed. The curly braces enclosing the block after the if are not optional. They are required!

  5. Program control continues here whether or not the if block was executed.


The if/else Construct

Another form of the if statement is the if/else construct. This construct allows for a two-way decision. If the first conditional expression following the if keyword is true, the block of statements following the if are executed. Otherwise, if the conditional expression following the if keyword is false, control branches to the else, and the block of statements following the else are executed. The else statement is never an independent statement. It must follow an if statement. When the if statements are nested within other if statements, the else statement is associated with the closest previous if statement.

Format

if (Expression)
      {Block}
else
      {Block}

Example 7.2.

(The Script)
1   print "What version of the operating system are you using? ";
2   chomp($os=<STDIN>);
3   if ($os > 2.2) {print "Most of the bugs have been worked
                           out!\n";}
4   else {print "Expect some problems.\n";}

(Output)
1   What version of the operating system are you using?  2.4
3   Most of the bugs have been worked out!

(Output)
1   What version of the operating system are you using?  2.0
4   Expect some problems.

Explanation

  1. The user is asked for input.

  2. The newline is removed.

  3. If the value of $os is greater than 2.2, the block enclosed in curly braces is executed. If not, program control goes to the else on line 4.

  4. If $os is not greater than 2.2, this block is executed.


The if/elsif/else Construct

Yet another form of the if statement is the if/else/elsif construct. This construct provides a multiway decision structure. If the first conditional expression following the if keyword is true, the block of statements following the if is executed. Otherwise, the first elsif statement is tested. If the conditional expression following the first elsif is false, the next elsif is tested, etc. If all of the conditional expressions following the elsifs are false, the block after the else is executed; this is the default action.

Format

if (Expression1)
      {Block}
elsif (Expression2)
      {Block}
elsif (Expression3)
      {Block}
else
      {Block}

Example 7.3.

(The Script)
1   $hour=(localtime)[2];
2   if ($hour >= 0 && $hour < 12){print "Good–morning!\n";}
3   elsif ($hour == 12){print "Lunch time.\n";}
4   elsif ($hour > 12 && $hour < 17) {print "Siesta time.\n";}
5   else {print "Goodnight. Sweet dreams.\n";}

(Output)
4   Siesta time

Explanation

  1. The scalar $hour is set to the current hour. The localtime built-in function returns the hour, the third element of the array of time values.

  2. The if statement tests whether the value of $hour is greater than or equal to 0 and less than 12. The result of the evaluation is true, so the block following the control expression is executed (i.e., the print statement is executed).

  3. If the first if test is false, this expression is tested. If the value of $hour is equal to 12, the print statement is executed.

  4. If the previous elsif test failed, and this elsif expression evaluates to true, the print statement will be executed.

  5. If none of the above statements is true, the else statement, the default action, is executed.


The unless Construct

The unless statement is similar to the if statement, except that the control expression after the unless is tested for the reverse condition; that is, if the conditional expression following the unless is false, the statement block is executed.

The unless/else and unless/elsif behave in the same way as the if/else and if /elsif statements with the same reversed test as previously stated.

Format

unless (Expression) {Block}
unless (Expression) {Block} else {Block}
unless (Expression) {Block} elsif (Expression)
   {Block}... else {Block}

Example 7.4.

(The Script)
1   print "How old are you? ";
2   chomp($age = <STDIN>);
3   unless ($age <= 21 ){  # If false, enter the block
4          print "Let's party!\n";
    }
5   print "You said you were $age.\n";
(Output)
1  How old are you? 32
4  Let's party!
5  You said you were 32.

-------------Run the program again -------------

(Output)
1  How old are you? 10
5  You said you were 10.

Explanation

  1. This example is exactly like Example 7.1 except the logic in the condition is reversed. We will test for false rather than true. The user is asked for his age.

  2. The scalar $age is assigned a value.

  3. The scalar $age is tested. Unless its value is less than or equal to 21 (i.e., the expression evaluates to false), then the block is entered and line 4 is executed.

  4. If the user is not 21 or older, this line is printed. The curly braces enclosing the block after the if are not optional. They are required!

  5. Program control continues here whether or not the if block was executed.


 

Example 7.5.

(The Script)
    #!/bin/perl
    # Scriptname: excluder
1   while(<>){
2       ($name, $phone)=split(/:/);
3       unless($name eq "barbara"){
            $record="$name\t$phone";
4           print "$record";
        }
    }
5   print "\n$name has moved from this district.\n";

(Output)
$ excluder names
igor chevsky    408-123-4533
paco gutierrez  510-453-2776
ephram hardy    916-235-4455
james ikeda     415-449-0066
barbara kerz    207-398-6755
jose santiago   408-876-5899
tommy savage    408-876-1725
lizzy stachelin 415-555-1234

barbara has moved from this district.

					  

Explanation

  1. The while loop is entered. It will read one line at a time from whatever filename is given as a command-line argument to this script. The argument file is called names.

  2. Each line is split by a colon delimiter. The first field is assigned to $name and the second field to $phone.

  3. The unless statement is executed. It reads: unless $name evaluates to barbara, enter the block; in other words, anyone except barbara is okay.

  4. All names and phones are printed with the exception of barbara.

  5. When the loop exits, this line is printed.

Previous Page Next Page