Wednesday, December 13

Activeperl Loop Statements

Google+ Pinterest LinkedIn Tumblr +

Basics of ActivePerl – Part 8

Introduction
This is part 8 of my series, Basics of ActivePerl. A loop is a set of statements that executes repeatedly until a specified condition is met. In ActivePerl, you have the do-while loop, the while loop and the for loop. We shall see what all these mean in this article. A loop itself is a statement that has other statements inside.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

The do-while Loop
Try the following code first:

use strict;

print “Content-Type: text/html\n\n”;

my $n = 0;

do
    {
        print $n; print “
        ++$n;
    } while ($n<5)

Let us look at what is in the code. Zero is assigned to a variable, $n. Then you have the do-while loop statement. The first thing in the statement is, do. This is an instruction to the ActivePerl Interpreter to execute what is inside the curly braces.

The interpreter executes statements in a program from top to bottom. The first statement to execute is the declaration and assignment of the variable, $n. The next statement is the do-while loop statement (construct). So, as soon as the interpreter sees, do, it executes all the statements in the curly braces. There are two statements in the block. The first one displays the value of $n. The second one increments, $n.

Now, after the second curly brace, you have the word, while. do and while are reserved words. They are instructions to the ActivePerl interpreter. After the word, while, you have a condition. So, do instructs the interpreter to execute the statements in the curly braces. Immediately after that the interpreter sees while. while evaluates the condition to see if the condition results in true. If it results in true (returns true), then the statements in the curly braces are executed again. The while condition is checked again; if it is true the block is executed again. This cycle repeats until the condition is false.

For the case above the start value for $n is zero. When the block is executed, zero is displayed and then the value of $n is increased to 1, from zero. As $n is 1, the while condition becomes, “while (1 < 5)”. This evaluates to true. So the block is executed again. This time, the value of $n is 1, the first statement in the block displays 1. The second statement increments the value of $n to 2. The while condition becomes,  “while (2 < 5)”, which is true. So the cycle repeats. The cycle keeps repeating and $n is incrementing. This continues until the while condition is, “while (5 < 5)”. Now this evaluates to false, and so the block is not re-executed again.

The highest value of $n displayed is 4, but $n arrives at a value of 5, since in the block, it is displayed before being incremented.

The syntax for the do-while statement is:

do
    {
        statements
    } while (condition) 

The while Loop Statement
The syntax for the while loop statement (construct) is

while (condition)
    {
        statements
    }

The while loop statement is almost the same as the do-while loop statement with the following difference: There is no do instruction for the while loop. With the while loop, if at the start, the condition evaluates to false, the block is never executed. For the do-while loop, the block is evaluated at least once (the first time).

The for Loop
In the first code of this part of the series, there are two main statements. The declaration and assignment statement and the do-while loop statement. These two statements can be combined, in another loop called the for-loop. This is the whole code in the for loop:

use strict;

print “Content-Type: text/html\n\n”;

for (my $n=0; $n<5; ++$n)
    {
        print $n; print ‘
    }

All we have in this code is the for-loop. The for loop begins with the reserved word, for, followed by parentheses, then the block to be executed. In the parentheses there are three expressions (statements), separated by semicolons.

In the parentheses, the first expression is the declaration and initialization of the variable, $n. The next expression in the parentheses is the while condition we had. What pushed the do-while loop to be repeating was the incrementing of $n, that is, ++$n. In the parentheses of the for-loop, this is the third expression. There were two statements in the block of the do-while loop. One of the statements is now in the parentheses of the for-loop. The other one goes into the block of the for-loop.

The difference between this for-loop code and the first code above is that if the while condition is false the first time, the for-loop will never execute. In this way the for-loop is closer to the while-loop than the do-while loop.

Just note that in the parentheses of the for-loop, the first $n is preceded with the reserved word, my. Generally, according to the philosophy of this series, whenever a variable is typed for the first time in code, precede it with, my.

Read and try the above code.

A simplified syntax for the for-loop is given below. The explanation is given after.

for ([initialExpression]; [condition]; [incrementExpression]) {
   statements
}

When a for loop executes, the following occurs:

1) The initializing expression, initial-expression, if any, is executed. This expression usually initializes (assigns a value to a variable) one or more loop counters. This expression can also declare variables.
2) The condition expression is evaluated. If the value of condition is true, the loop statements will execute. If the value of the condition is false, the for loop ends. If the expression for the condition is omitted, the condition is assumed to be true.
3) The block statements execute.
4) The increment (or update) expression, if there is one, executes, and control returns to Step 2. 

The last Command
The “last;” statement (command) can be used to terminate a loop before its determined end. Try the following code and note that the loop ends after $n is 2.

use strict;

print “Content-Type: text/html\n\n”;

for (my $n=0; $n<5; ++$n)
    {
        print $n; print ‘
        if ($n == 2)
            {
                last;
            }
    }

Each time in the loop, the if-condition is checked for the value of true. When $n is 2, the if-condition will return true; making the if-block to execute. In the if-block, you have just one statement, the last statement. It is just one word, last. Always end the last statement and other statements with a semicolon. The last statement stops the loop from repeating. In this case it stopped the loop when the internal if-condition occurred (was true).

The next command
You can cause an iteration to be skipped as the loop is repeating. You use the next statement for this. It is just one word, next. Always end it with a semicolon. The following code illustrates this, when $n is 2. The iteration for $n equal 2 is skipped.

use strict;

print “Content-Type: text/html\n\n”;

for (my $n=0; $n<5; ++$n)
    {
        if ($n == 2)
            {
                next;
            }
        print $n; print ‘
    }

In order to skip the iteration of the block, you put the next statement and its condition at the beginning of the block.

This is how the next statement behaves:

– In a while loop, it jumps back to the condition.
– In a for loop, it jumps to the update (increment) expression.

We have come to the end of this part of the series, we continue in the next part.

Chrys

To arrive at any of the parts of this series, just type the corresponding title below in the Search Box of this page and click Search (use menu if available):

Getting Started with ActivePerl
ActivePerl Basic Syntax
Basics of ActivePerl Variables
ActivePerl Conditional Statements
Boolean Logic for ActivePerl
Boolean Logic and ActivePerl Conditions
ActivePerl Comparison and Arithmetic Operators
ActivePerl Loop Statements
ActivePerl Arrays
ActivePerl Hashes
ActivePerl Variable Types and Context
ActivePerl Subroutines
ActivePerl foreach loop
Introduction to ActivePerl Special Variables
Basics of ActivePerl Variable Scope
Some ActivePerl Predefined Subroutines
White Space in ActivePerl
Basics of ActivePerl Reference
Error Basics in ActivePerl
File Accessing Basics in ActivePerl
Sending HTML Form with ActivePerl
 

Share.

About Author

Leave A Reply