Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
Perl provides following ways for executing the loops.
1) While:
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
Output: 1 2 3 4 5 6 7 8 9
2) Do while:
do while loop is similar to while loop with only difference that it checks for condition after executing the statements.
Output: 11 12 13 14 15 16 17 18 19
3) Until:
Repeats the statements inside its body till its condition is false.
Output: 0 1 2 3 4 5
4) for:
for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
Output: Hello Hello Hello Hello Hello
5) for-each:
A foreach loop is used to iterate over each element of a list.
Perl provides following ways for executing the loops.
1) While:
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
1 2 3 4 5 6 7 | $a=1; #While loop while($a<10){ print "$a "; $a=$a+1; } |
2) Do while:
do while loop is similar to while loop with only difference that it checks for condition after executing the statements.
1 2 3 4 5 6 7 | $a=11; #Do while loop do{ print "$a "; $a=$a+1; }while($a<20); |
3) Until:
Repeats the statements inside its body till its condition is false.
1 2 3 4 5 6 7 8 | $a=0; #until loop #Repeats the statements inside its body till its condition is false until ($a>5){ print "$a "; $a = $a+1; } |
4) for:
for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
1 2 3 4 | #For loop for ($a = 1 ; $a <= 5 ; $a ++ ){ print ( "Hello " ) ; } |
5) for-each:
A foreach loop is used to iterate over each element of a list.
1 2 3 4 5 | @list = (10, 20, 30, 40, 50); #For each loop foreach $a (@list) { print "value of a: $a\n"; } |
This comment has been removed by a blog administrator.
ReplyDelete