In the last tutorial, we discussed for loop in Perl. In this tutorial we will discuss while loop. As discussed in previous tutorial, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
Syntax of while loop:
while(condition) { statement(s); }
Flow of Execution of the while Loop
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute. When condition returns false, the control comes out of loop and jumps to the next statement after while loop.
Note: The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely.
Example
#!/usr/local/bin/perl $num = 100; while( $num > 95 ){ printf "$num\n"; $num--; }
Output:
100 99 98 97 96
Leave a Reply