In usual execution, the code is executed sequentially, line-by-line. Loops in Perl are control structures that allow users to run a block of code multiple times.
Perl offers the following types of loops:
Loop type | Description |
while loop | While loop repeatedly executes a block of code while the given condition stays true. It checks the condition before running the block of code. |
until loop | Until loop repeatedly executes a block of code until the given condition becomes true. It checks the condition before running the block of code. |
for loop | For loop repeatedly executes a block of code the number of times set by a counter variable. It checks the condition before running the block of code. |
foreach loop | Foreach loop uses a list to iterate over. It sets the variable to be each element of the list in turn. |
do-while loop | Do-while loop repeatedly executes a block of code while the given condition stays true. It checks the condition after running the block of code. |
nested loop | Nested loops are when you use a loop inside another loop. |
The following code shows how different loops can be implemented.
print("while loop example:\n"); my $counter = 1; while($counter <= 5){ #condition to check print("$counter\n"); # increment counter variable $counter++; } print("for loop example:\n"); my @a = (1..5); for my $i (@a){ # counter variable $i print("$i","\n"); } print("foreach loop example:\n"); my @list = (1..5); foreach(@list){ # iterate over the list print("$_","\n"); }
RELATED TAGS
CONTRIBUTOR
View all Courses