In this tutorial, we will learn about for loops in Perl. We will cover the basics of iterative execution using for loops.
A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop is typically used when the number of iterations is known before entering the loop.
The syntax for the for loop in Perl is:
for (initialization; condition; increment) {
# Code block to be executed
}
The for loop evaluates the initialization statement, then the condition. If the condition is true, the code block inside the loop is executed. After each iteration, the increment statement is executed, and the condition is re-evaluated. This process repeats until the condition becomes false.
for (my $i = 1; $i <= 10; $i++) {
print "$i ";
}
1 2 3 4 5 6 7 8 9 10
my $n = 5;
my $factorial = 1;
for (my $i = 1; $i <= $n; $i++) {
$factorial *= $i;
}
print "Factorial of $n is $factorial\n";
Factorial of 5 is 120
my @arr = (1, 2, 3, 4, 5);
my $sum = 0;
for my $element (@arr) {
$sum += $element;
}
print "Sum of the elements in the array is $sum\n";
Sum of the elements in the array is 15