Flag This Hub

Learning Perl Fundamentals - Chapter 12

By


for Loop

The ‘for’ loop is a commonly used control structure in Perl. It is similar to the ‘while’ loop, but it allows you to initialize a counter and increment it for each execution of the code block. The syntax for writing a ‘for’ loop is similar to that of other control structures. In this hub, you would learn to create a ‘for’ loop.

A ‘for’ statement allows you to repeat the execution of a code block a specific number of times. You usually use a variable that acts as a counter for the loop.  For example, to load five images on to a Web page, you can use the ‘for’ loop to initialize a counter that loads an image each time for five iterations of the loop.

for ($counter=0;$counter<5;$counter++)

The ‘for’ loop includes three expressions. The first expression is known as the initialization expression. This expression initializes the counter variable to contain a certain value, usually zero or one.

The second expression specifies the condition on which the block continues to be executed. The condition usually examines or compares the value of the counter variable. If the condition is found to be true, the specified code block is executed.

The third expression normally modifies the value of the counter variable. It is typically used to increment or decrement the counter.

In the following example, the loop is executed for each value of ‘i’ that is between zero and nine. Each time the loop is executed, the value of ‘i’ is incremented by one. Each expression inside the parentheses is separated by a semicolon.

In the following example, the ‘for’ loop prompts the user for a number. The loop is executed ten times. Each time it is executed, the new number is added to the previous numbers to produce a running total. The current total is printed to a terminal window by the loop each time the block executes.

In this hub, you learned about ‘for’ loop. The ‘for’ loop is executed a specific or dynamic number of times until a condition is satisfied. The ‘for’ loop typically initializes a counter, examines the condition for the loop to be executed, executes a specified block of code if the condition is true, and increments the counter each time.

Comments

No comments yet.

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working