In this tutorial we will learn how to use “for loop” in Perl. Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
Syntax of for loop:
for(initialization; condition ; increment/decrement) { statement(s); }
Flow of Execution of the for Loop
As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program.
First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
Example:
#!/usr/local/bin/perl for( $num = 100; $num < 105; $num = $num + 1 ){ print "$num\n"; }
Output:
100 101 102 103 104
Leave a Reply