Introduction to Internet Programming with Perl and HTML: Part 4 – Basic Perl Flow-Control Syntax

Published: January 22nd, 2010


This article is Part 4 of our series on Internet Programming. See the Introduction and Part 1, Introduction to HTML. This article covers logical comparisons,
making decisions with if, comparing text, while and for loops, and debugging hints.


4.1 Making Comparisons

In the last session when we used the “=” operator it was for
assignment — to store a value in a variable. It did not ask the
question as to whether the variable already has that value. Asking
questions about the contents of variables or the results of calculations
is called making a comparison. Perl has lots of operators specially
designed for allowing you to make comparisons – you will recognize many of them:

$x == $y
Is $x numerically EQUAL to $y?
[We need the double == here to
differentiate from the singe = which
would mean store the value of $y in $x.]

$x != $y
Is $x numerically NOT EQUAL to $y?

$x < $y
Is $x numerically LESS THAN $y?

$x <= $y
Is $x numerically LESS THAN or EQUAL to $y?

$x > $y
Is $x numerically GREATER THAN $y?

$x >= $y
Is $x numerically GREATER THAN or EQUAL TO $y?

question1 && question2
Are the answers to BOTH question1 AND question2 true?

question1 || question2
Is the answer to EITHER question1 OR question2 true?

! question1
Is the answer to question1 NOT true (i.e. is it false)?

In the above table, the variables $x and $y can be ANY
variable, number or expression that evaluates to a number; question1 and question2
can be any expression containing one of the above comparison operators. For example,
to see if the average of 2 numbers, $x and $y, is less than 25,
you could use

($x + $y)/2 < 25

This evaluates to TRUE if it is the case and FALSE if it is not the case. Now, in Perl,
false means “zero” and true means “not-zero” for numbers. So, if you print this

print ( ($x + $y)/2 < 25 );

It will not print the words true of false, but some number indicative
of the truth or falsity. Just like there is an order of operations when
performing mathematical operations like addition and multiplication, the
order of operations extends to comparisons. The order of operations for
all the symbols that you know so far is:

**             Exponentiation
-              Negation
* / %          Multiplication, Division, Modulus
+ - .          Addition, Subtraction, Concatenation
< > <= >=
== !=
=              Assignment

If you want to calculate something that requires violating the order of operations,
then you have to use parenthesis. I.e. say you want to be sure that $x or $y
is greater than zero and $x or $y is less than ten. You could write

$x > 0 || $y > 0 && $x < 10 || $y < 10

However, because AND has higher priority than OR, this expression is true if 1.
$x > 0, OR 2. $y > 0 AND $x < 10, OR 3.
$y < 10, which is NOT what we intended. To get what we intended, we need
to use parenthesis to change the order of operations:

($x > 0 || $y > 0) && ($x < 10 || $y < 10)

4.2 Using Comparisons to Make Decisions

Comparisons by themselves are not very useful unless we can act on the results! Like most
programming languages, Perl comes with a way of performing different actions based on the
results of a condition. That is the if statement. An if statement takes
the form:

if (condition) {

Inside the parenthesis, you place one of the comparisons we just learned about or join
multiple comparisons together with the operators for OR and AND. Inside the curly brackets,
you can place one or more Perl statements of any type. A simple example of how this might work
is the following:

print "Pick a number between 1 and 10:";
$x = <STDIN>;
if ($x == 6) {
   print "You guessed it!\n";
if ($x != 6) {
   print "Nope, that's not it!\n";

You can see that you may often have multiple things to test. Perl’s if
statement is a bit more versatile, it lets you chain if statements together…

print "Pick a number between 1 and 10:";
$x = <STDIN>;
if ($x == 6) {
   print "You guessed it!\n";
elsif ($x == 5 || $x == 7) {
   print "You're warm!\n";
else {
   print "You're cold!\n";

print "Try Again.\n";

The elsif is read “Else, IF” or “Otherwise, If”. If the condition in the
first statement is false, then the condition in the next statement is tested. It it is false,
we hit the else line which is read “Otherwise, Do This”, or “If all those previous
conditions failed, then do this”. You can have as many elsif statements as you
want in a row (or none) following the first if. You don’t have to have an
else statement at the end, but if you do, you can only have one of them. We could have
implemented our earlier example with an else:

print "Pick a number between 1 and 10:";
$x = <STDIN>;
if ($x == 6) {
   print "You guessed it!\n";
else {
   print "Nope, that's not it!\n";
print "Try Again.\n";

If one of the blocks of statements in the if..elsifelse
are executed, then you may wonder what happens when the last statement in the block is
over. At that time, the program continues with the next line
after the if..elsifelse statements.
In both cases above, no matter what the user enters, he gets some single
message as to how close his guess was, then he (or she) gets told to “Try Again”.

Debugging Help:

  • Be sure to use curly brackets, and that if you have a left curly bracket, that you
    include the right curly bracket to match it.

  • Curly brackets are NOT parenthesis, even though they look alike if you are far from
    the screen.

  • “Else If” is the statement “elsif” and NOT “elseif“. You can say
    else if” but you shouldn’t as there is a subtle difference making the former
    method better.

  • Case matters: Use all lower case letters for if, elsif, and else.
  • If you don’t know if you program executed a particular block of Perl statements inside
    your if, add some extra print statements in there to see. You can always
    delete them or comment them out later once everything works perfectly.

4.3 Comparing Text

Perl allows you to compare text as well as numbers. It has several special operators
for comparing text. Some of these are

$x eq $y
Is $x lexically EQUAL to $y?

$x ne $y
Is $x lexically NOT EQUAL to $y?

A lexical (text) comparison looks at the individual characters in the text and does
not think about numbers AT ALL. I.e. “1.5” and “1.50” are numerically equal, but lexically
not equal because the second string (piece of text) has an extra zero. These operators have
the same priority (in terms of the order of operations)
as the numerical “==” and “!=” operators described above.

Perl will not complain if you try to compare numbers and strings or strings and strings
using the numerical comparison operators. It will just convert your string into a number
first and then do the comparison. It does this by looking for numbers at the beginning
of the string. So, “55” and “55slkdfjh” will both get treated as “55”. But “sddkjh55” will be
treated as ZERO since there are no numbers at the beginning. And, “fifty-five” is also
treated as “zero” by numerical comparisons (and mathematical operators). So be CAREFUL:

"Erik" < 5;       ## True since "Erik" is numerically 0
"5x45" < 5;       ## False since "5x45" is numerically 5
"John" + 3;       ## Equals "3" since "John" is numerically 0
"John" eq "John"  ## True
"John" eq "John " ## False because of the extra space on the end

In general, you should use the numeric operators for numbers and the string
operators for strings. Otherwise, be very careful.

Two functions that you will find useful when using strings are uc and
lc. These take a string and return the upper case and lower case versions
of that string, respectively. I.e.

print lc("John Smith");    # prints "john smith"
print uc("John smith");         # prints "JOHN SMITH"
uc("Erik") eq "ERIK"            # is True

These two functions are really good for examining user input in a
case-insensitive fashion so your programs are more user friendly.
Consider the example of asking the user if he wants to continue:

print "Would you like to continue (yes or no) ?";
$answer = <STDIN>;
if (lc($answer) eq "yes") {
    # Continue

In this example the user can answer "Yes" or "yes" or "YES" and it would
still be OK. This is a good thing. However, we have no way yet to
force the user to answer yes or no. To do this we need some kind of loop
where we can go back and ask again if they didn't enter a valid answer...

4.4 Loop the Loop

Finally, we can discuss one of the most powerful parts of programming... making a loop.
A loop is a way to specify that some action or actions should be repeated until some
condition is met. In Perl, the simplest loop is the while loop, which has the
following syntax:

while (condition) {

This looks a lot like the if statement in that IF the condition is true, the
statements inside the curly brackets will be executed. It differs from an if in
that once the statements are done being executed, the condition is evaluated again. If it is
still true, then the statements are executed again, etc. until the statement is false.
You can see that if you are not careful to make sure that you statement will eventually be false,
your loop could run forever -- an infinite loop. You should avoid infinite loops!
Here is an example of an infinite loop:

$x = 1;
while ($x == 1) {
   print "\$x is One!\n";

Since we never change the value of $x inside the loop, the condition
will ALWAYS be true, and this will print "$x is One!\n" until you stop
it by pressing Control-C or by turning off your computer or something!
A more realistic example allows you to count from 1 to 10:

$x = 1;
while ($x < 11) {
   print "$x\n";
   $x = $x + 1;

In this example, we increment $x in each iteration of the loop, so it eventually is
no longer less than eleven and the loop ends, having printed the numbers one through ten.

Going back to asking the user if he want's to continue, we can now do this right...

print "Would you like to continue (yes or no) ?";
$answer = "";
while (lc($answer) ne "no" && lc($answer) ne "yes") {
   $answer = <STDIN>;

if (lc($answer) eq "yes") {
    # Continue
else {
    # Stop

As you can imagine, the previous example illustrates something that we do with loops all the time:

  1. Initialize a variable, i.e. $x = 1;
  2. Test a condition, i.e. $x < 11;
  3. Perform some statements
  4. Prepare for the next iteration, i.e. $x = $x + 1;

Perl has another kind of loop called the for loop that simplifies the
description of these common actions, its syntax is:

for (initialization; condition; final statement) {

Where the 4 standard parts of a loop fit right in, i.e.

for ($x = 1; $x < 11; $x = $x + 1) {
   print "$x\n";

The "$x = 1;" is performed first and only once; the "$x
< 11;
" is checked before each iteration and must be true for the iteration
to take place; "$x = $x + 1" is performed after each iteration,
before the condition is checked.

Here is a nice example that computes the sum of the squares of the numbers
from 1 to 100:

$sum = 0;

for ($n = 1; $n <= 100; $n = $n + 1) {
   $sum = $sum + $n ** 2;

print "The sum is $sum\n";

Debugging Hints:

  • If you run into an infinite loop, press Control-C to stop
    your program

  • If you mean to use == to compare if two things are equal,
    be sure that you don't accidently use =. This will perform
    an assignment, changing the value of your variable and NOT perform
    any comparison at all. You won't get an error, but you will almost certainly
    get the wrong answer!

  • Use print statements to help debut -- put them inside your
    loops so you can watch the loops execute and view how the contents of
    your variables are changing.

Ending Your Loops: When writing loops, it is often very
useful exit a loop early, or to go on to the next iteration early.
The Perl command "last" exits the current loop and
Perl continues execution at the next statement after the loop. The
command "next" causes Perl to consider this the last statement in
the loop. For for loops, the "preparation" statement
is executed and then the condition is tested to see if the
loop should continue to iterate. For while loops,
Perl immediately proceeds to testing the condition.

Related to ending loops is a command for ending your Perl program.
If you use the command "exit", Perl will end your program

$x = 1;

## Here is an "infinite loop" we exit using the "last"
## command.

while ($x == 1) {
   $a = <STDIN>;
   if (lc($a) eq "yes" || uc($a) eq "NO") {
      last;    ## Exit the loop
   next;       ## Goto the next iteration

   print "This will never be printed!\n";

print "All done!\n"

exit;          ## End the program now.

print "This will never be printed either!\n";

4.5 Your Homework

  1. Write a script that asks the user a multiple choice question, reads the
    user's input, and then tells him if he is right or wrong. If it was wrong,
    ask the question again and again until the person gets it right.

  2. Write a program that calculates the average of a series of numbers
    entered by the user. You should use a loop to ask the user for
    a number (or to type something like "exit" to stop entering numbers and
    exit the loop). For each number entered, update the a variable
    containing the sum of all numbers,
    and a variable containing the total number of numbers entered.
    Then, when the loop is over,
    you can divide these two to compute and display the average/
    Note - but what if they did not enter ANY numbers ...?


One Response to “Introduction to Internet Programming with Perl and HTML: Part 4 – Basic Perl Flow-Control Syntax”

  1. swathi Says:

    hi will u pls sent me to how to write a progremm of having the NO 1 to 100 without using any loops pls pls..
    and also the programm to exsicute both if &else pls pls.. help me pls.

Leave a Comment

You must be connected or logged in to post a comment. This is to reduce spam comments.

If you have not previously commented, you can connect using existing social media account, or register with a new username and password.