for loop in perl

The for loop is a common looping construct in Perl that allows you to execute a block of code repeatedly for a fixed number of times, or to iterate over a list of values.

Here's the basic syntax of the for loop in Perl:

re‮gi:ot ref‬iftidea.com
for (initialization; condition; increment) {
    # block of code to be executed repeatedly
}
  • initialization: This is where you initialize a variable that will be used as a loop counter. You can also initialize multiple variables separated by commas.
  • condition: This is the condition that is evaluated at the beginning of each iteration of the loop. If the condition is true, the loop continues; if it is false, the loop terminates.
  • increment: This is where you increment or decrement the loop counter. You can also modify multiple variables separated by commas.

Here's an example of a for loop that prints the numbers from 1 to 10:

for (my $i = 1; $i <= 10; $i++) {
    print "$i\n";
}

In this example, the variable $i is initialized to 1. The loop continues as long as $i is less than or equal to 10. After each iteration of the loop, $i is incremented by 1. The print statement within the loop will be executed 10 times, each time with the value of $i increasing from 1 to 10.

You can also use the for loop to iterate over a list of values. For example, the following for loop prints each item in an array:

my @fruits = ('apple', 'banana', 'orange', 'pear');
for my $fruit (@fruits) {
    print "$fruit\n";
}

In this example, the loop iterates over the array @fruits, assigning each item in the array to the variable $fruit. The print statement within the loop will be executed 4 times, once for each item in the array.