Perl | Loops (for, foreach, while, do…while, until, Nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are :
“for” loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
Syntax:
for (init statement; condition; increment/decrement )
Flow Chart:
A for loop works on a predefined flow of control. The flow of control can be determined by the following :
- init statement: This is the first statement which is executed. In this step, we initialize a variable which controls the loop.
- condition: In this step, the given condition is evaluated and the for loop runs if it is True. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
- Statement execution: Once the condition is evaluated to true, the statements in the loop body are executed.
- increment/decrement: The loop control variable is changed here (incremented or decremented) for updating the variable for next iteration.
- Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.
Example :