Beginning CGI Programming with Perl

Exercise 3.2. The Perl conditional statement if(){} else{}

Your computer reads your Perl program one line at a time. It does exactly what each line tells it to do. Your mind often is referred to as the most complex computer imaginable. Now, for some people, that might be overly generous, but for the sake of this discussion, let’s accept that the mind is like a computer.

Using that analogy, if you wrote a program to tell your body to walk, the program might be a series of instructions telling your legs to put one foot in front of the other. This simple program would work just fine if all you had to do was walk in a straight line, but occasionally you will need to stop or change directions. The conditions that cause you to change directions or stop are the conditional statements of a program. I might want to tell my program that if there is a brick wall in front of me, turn left or right, depending on other conditions; otherwise, keep going straight. Lots of different conditions can be strung together to determine whether I want to turn right or left.

That might seem like a lot of discussion without any programming information, but really you just learned about the basics of Perl programming conditional statements. The fundamental Perl conditional statement is the if statement, which looks like this when used with the walking program:

if (a brick wall is in front of me) {turn left}else {keep going}

This exercise examines the if and the else statements. The if statement here contains all the parts of a complex if statement:

  1. The if keyword: if
  2. An expression of the condition: (a brick wall is in front of me)
  3. The block of statements to execute when the condition statement is true: {turn left}

In Perl, the statement to execute is called a block because it can include more than one statement, and each statement can be any valid Perl statement. The block of statements after the conditional expression is executed only if the conditional expression is determined by the computer to be true. The exact format of the if statement follows:

if (condition expression){block of statements}

The conditional expression must be surrounded by opening (() and closing ()) parentheses. The block of statements must be surrounded by curly braces ({}). In Listing 3.9, you’ll work through a complete example that uses different combinations of the if, else, and elsif statements.


You will see lots of different styles for indenting the block of statements after the if condition expression, and some people are very adamant that their way is best. This is really an argument over what is the best color for your car. If you like blue, black, or red, it really is best for you to get that color car, but the car will run just the same.

As I have said previously and will say again: It is important to pick a style and use it. You pick the style. Here are several styles for formatting if, else statements.

  1. if (condition expression){
    block of statements}
  2. if (condition expression){
    block of statements
  3. if (condition expression){
    block of statements
  4. if (condition expression)
    block of statements

And I could go on about the number of spaces to indent your block of statements, but I won’t. I will tell you this: Don’t use tabs. Tab characters are viewed differently by every machine, even when they are the same type of machine, because the tab stops are set by each user for his word processor. Use spaces to indent your code.

If you’re curious, I prefer the third style, but the first one I listed is probably the most popular.

Listing 3.9. Using the Perl if else elsif statements.

01: #! /usr/local/bin/perl02:03: # some of these variables are zero based:04: # 0-59     0-59     1-24   1-31           0-1105: ($second, $minute, $hour, $day_of_month, $month,06: # 0-99   0-6        1-366        0,107:  $year, $weekday, $day_of_year, $daylight_standard_time) = localtime(time);08:09: #is the month december and the day the 24th or 25th?10: if ( ($month == 11) && ($day_of_month == 24 || $day_of_month == 25) ){11:    print "Merry Christmas, World \n";12:    }13: else{14:     # is it after 6pm15:     if ($hour > 18){16:         # is it after 6pm and before 9pm17:     if ($hour < 21){18:        print "Good Evening, World\n";19:        }20:         # then it must be after 9pm but before midnight21:     else {22:        print "Good Night, World\n";23:        }24:         } #end if hour > 1825:     elsif ($hour > 12){26:         print "Good Afternoon, World\n";27:         }28:     elsif ($hour > 6) {29:         print "Good Morning, World\n";30:         }31:     # if is between 6am and midnight32:     else{33:         print "Go to BED already! \n";34:         }35:     }

This is a relatively long example, but you’ll work through most of it one step at a time. By the time you’re done with this section, you should feel comfortable with the code here.

Let’s start with lines 3-7. This is really just one line of code. The lines beginning with the number sign (#) are comments and are not executed by the computer. Comments are used to help the programmer remember what is going on. Lines 3-7 could be rewritten, using shorter variable names and without comments, like this:

($sec, $min, $hr, $mntdy, $mon, $yr, $wk, $yrdy, $stm) = localtime(time);

Both this line and lines 3-7 do exactly the same thing. I have problems with this line, though. Even with more readable variable names, I would have a hard time remembering which variables start at 0 and what each variable’s range is. I like comments; they help me a lot after I have slept for an hour or two. Lines 3-7 are kind of like assigning data to the array cells of a regular array, which you learned about in Exercise 2.1. In that exercise, line 3 assigned a list to a regular array:

@my_name = ("Eric ","C. ","Herrmann");

The localtime function on line 7 creates a nine-element array. Instead of assigning the data to an array, however, you assign the data to a list of scalar variables:

($second, $minute, $hour, $day_of_month, $month, $year, $weekday,  $day_of_year, $daylight_standard_time)

All the data returned by localtime is integer data. Most of the values start at 0. This is supposed to help you index through arrays of the names of months or days of the week. It seems kind of weird that December is the 11th month of the year. But that’s how it works, because the first month of the year, January, is month zero.

The function localtime() is part of the Perl distribution library. The parameter time in localtime(time) is actually another Perl function that returns the current time in number of seconds since January 1, 1970. The function localtime() then converts that time into the nine elements of data on the left-hand side of the equal sign.

The complex if statement on lines 10 and 11 could be read as the following:

If the month is December and the day is the 24th or the 25th, then say

Merry Christmas, World

The condition expression ($month == 11) is evaluated or read first. The computer checks to see whether the variable $month equals 11 (because the month of December is represented by the value 11).


You use the double equal sign (==) to tell the computer that you want to compare the variable $month as an integer. If you want the computer to compare your variable equal to a character string, you use the eq operator, as in this example:

if ($month eq "december")

The operator && is read as AND by your computer. The operator || in the next portion of the condition expression is read as OR by your computer. There is a set of parentheses around the $day_of_month checks so that the computer evaluates the conditional expression to True only if both the month is December (11) and the day is either the 24th or the 25th. So take a moment to reread line 10. You should be able to follow it now: If the $month variable is equal to December, and the $day_of_month variable is 24 or 25. The parentheses around the $day_of_month expression can be read as the either part (either this or that).

If it is December 24th or 25th, your computer prints Merry Christmas, World. Otherwise, the condition expression on line 10 evaluates to False and the computer skips the block of statements that begins with the opening curly brace ({) at the end of line 10 and ends with the closing curly brace (}) on line 12.

If the conditional expression evaluates to False, the next block of statements the computer executes is the else block from lines 13-35. An else block does not have a condition expression; it is executed whenever the if statement evaluates to False. An if statement does not require an else block.

An if statement can look like this:

if (condition expression){block of statements}

An if statement like this is evaluated and, if it is True, the block of statements is executed and then the statements following the block of statements are executed.

In an if else clause such as

if (condition expression){block of statements}else{block of statements}

if the if (condition expression) evaluates to True, the computer executes the block of statements following the if (condition expression). If the if (condition expression) evaluates to False, the computer skips the block of statements following the if (condition expression) and executes the block of statements following the else statement.

So, in Listing 3.9, only one of the print statements is printed each time you run the program.

Let’s assume that it is not December 24th or 25th, which means that you will skip the block of statements beginning on line 11 and begin to execute the block of statements that begins on line 14. (Actually, the block of statements begins with the opening curly brace ({) on line 13. Each of these condition expressions is very similar, so after you get the first one, you should understand the rest.

The first statement inside the else block of statements is another if statement. You can have any type of statements inside a block of statements. The if statement checks whether the $hour variable is greater than 18 by using the greater than (>) operator. The block of statements following this if statement extends from lines 16-24 and includes another if check. Read the comments that go along with the code to follow along and understand what is happening.

If the condition expression on line 15 evaluates to False, the next statement to execute is line 25-an elsif expression. elsif statements are really the equivalent of an if else statement but sometimes make your code more readable; this is a good example of such a time. In this case, the hour is not greater than 18, so it must be between 0 and 18, so now you check for each block of time that usually is associated with a greeting. Is it after noon? If not, is it after 6 a.m.? If not, it must be between 0 and 6 a.m. I usually take time to write down in English what is happening in a complex if, elsif, or else expression. It helps me make sure that my code is doing what I really want it to do.

Starting from the else block beginning on line 13, the English that describes what you want this code to do follows:

otherwiseif the hour is greater than 6pm thenif the hour is less than 9pmprint Good Evening, Worldotherwise the hour must be between 9pm and midnightso print Good Night, World.otherwise if the hour is greater than noon but less than 6pmprint Good Afternoon, Worldotherwise if the hour is greater than 6ambut less than 6pm and less than noonprint Good Morning, Worldotherwise the hour must be between midnight and 6amso print Go to BED already!

If this program were written as blocks of statements and conditional expressions, it would look like this:

if (condition expression) {block of statements1}else {block of statements2}

{block of statments2} looks like this:

if (condition expression){block of statements3}elsif(condition expression){block of statements4}elsif(condition expression){block of statements5}else{block of statements6}{block of statments3} looks like this:if(condition expression){block of statements7}else{block of statements8}

The unexpanded {block of statements} are simple print statements with no condition expression inside them.

During this exercise, you learned about statements that cause the computer to choose between different blocks of statements to execute. The basic syntax of those statements follows:

  • if (condition expression){block of statements}
  • if (condition expression){block of statements} else {block of statements}
  • if (condition expression){block of statements} elsif {block of statements} ...

The elsif statement can be repeated as often as desired.

  • if (condition expression){block of statements} elsif {block of statements} ... else {block of statements

Leave a Reply

Your email address will not be published. Required fields are marked *