Different loops in Perl
There are many cases when we need to execute a block of code a certain number of times of times. In general, statements are executed in ore; the first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times using a loop statement in most of the programming languages. Perl provides these loop statements. The loop statement consists of a condition and if the condition is true, it executes the code block.
While and do .. while loops
The while statement executes a block of code until a specific condition is met. In the while loop, a condition is check and if true, the code block is executed. If the condition in a while loop fails from the beginning, the code block is never executed. To ensure that the code block gets executed at least once, we can use a do .. while loop which will execute the code block first and then check the condition. As with while loops in C, Python and other languages, if the condition never evaluates to false, the loop will go on infinitely.
While loop
$count = 10; while ($count > 0) { print "$count "; $count--; }
Will output 10 9 8 7 6 5 4 3 2 1
Do .. while
$count = 10; do { print "$count "; $count--; } while ($count > 0)
Will output 10 9 8 7 6 5 4 3 2 1
Infinite loop
$count = 10; $count2 = 5 while ($count2 > 0) { print "$count "; $count--; }
Will output 10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 ... infinitely
For loop and foreach
The for loop repeats a block of code until a certain condition is met. It is typically used to execute a block of code for certain number of times. This loop is preferred when we are sure about the number of iterations of the script. The parameters of for loop three meanings. Th first is initialization, used to initialize the counter variables and evaluated once unconditionally before the first execution of code block. Next is the condition which is the beginning of each iteration. If it evaluates to true, the loop continues and the nested statements are executed. If it evaluates to false, the execution of the loop ends. Lastly, he increment updates the loop counter with a new value. It is evaluate at the end of each iteration. The foreach loop iterates over a list value and sets the control variable (var) to be each element of the list in turn.
for loop
for( $num = 1; $num < 5; $a = $num + 1 ) { print "$num"; }
foreach
@list = (1, 2, 3, 4, 5); foreach $num (@list) { print "$numb "; }