Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

perl

What are loops in Perl?

Sheza Munir

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.

Types of loops

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.

Code

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

perl

CONTRIBUTOR

Sheza Munir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring