There may be a situation when you need to execute a block of code several times. Perl provide various control structures that allow for more complicated execution paths.
Perl provides the following types of loop to handle the looping requirements.
while loop
This loop is used to repeat a statement or group of statements while a given condition is true. It tests the condition before entering the block.
until loop
This loop is also used to repeat a statement or group of statements until a given condition becomes true. It tests the condition before entering the block.
for loop
This loop also executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
foreach loop
The foreach loop iterates over a normal list value and sets the variable to be each element of the list in turn.
do...while loop
Like a while statement, except that it tests the condition at the end of the loop body
Loop Control Statements
Different loop control statements used in Perl are discussed below.
next statement
It is used to skip the remaining lines of it's enclosing loop and moves the control to the next iteration immediately.
last statement
It terminates the loop statement and transfers execution to the statement immediately following the loop.
continue statement
Let us try the following code to understand continue statement.
redo statement
The redo command restarts the loop without evaluating the condition. The continue block, if any, is not executed.
goto statement
Perl supports a goto command with three forms: goto label, goto expr, and goto &name.
The Infinite Loop
If the condition of a loop never becomes false, the loop runs for infinite time.
You can terminate the above infinite loop by pressing the
Ctrl + C
keys.
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but as a programmer more commonly use the for (;;) construct to signify an infinite loop.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.