In this tutorial, we will learn about different types of loops in Perl. We will cover the basics of for, while, and do-while loops.
A loop is a control flow statement that allows code to be executed repeatedly based on a condition.
Perl supports three types of loops: for loops, while loops, and do-while loops.
A for loop (also known as a foreach loop in Perl) is used when the number of iterations is known before entering the loop. The syntax for the for loop is:
for (initialization; condition; increment) {
# Code block to be executed
}
A while loop is used when the number of iterations is not known beforehand. The syntax for the while loop is:
while (condition) {
# Code block to be executed
}
A do-while loop is similar to a while loop, but it guarantees that the code block will be executed at least once. The syntax for the do-while loop is:
do {
# Code block to be executed
} while (condition);
$i
.for (my $i = 1; $i <= 10; $i++) {
print "$i ";
}
1 2 3 4 5 6 7 8 9 10
$i
and initialize it to 1.my $i = 1;
while ($i <= 5) {
print "$i ";
$i++;
}
1 2 3 4 5
$i
and initialize it to 1.my $i = 1;
do {
print "$i ";
$i++;
} while ($i <= 3);
1 2 3