perl foreach loop

The foreach loop in Perl is used to iterate over a list or an array. It allows you to execute a block of code for each element in the list or array.

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

refer ‮igi:ot‬ftidea.com
foreach my $element (@list) {
    # block of code to be executed for each $element in @list
}

In this syntax, $element is a scalar variable that takes on the value of each element in @list during each iteration of the loop. The keyword my is used to declare $element as a lexical variable that is local to the loop block. You can use any scalar variable as the loop variable, but it is a good practice to use a meaningful variable name that describes the elements you are iterating over.

Here's an example of a foreach loop that prints the elements of an array:

my @fruits = qw(apple banana cherry);
foreach my $fruit (@fruits) {
    print "$fruit\n";
}

In this example, the array @fruits contains three elements. The foreach loop iterates over each element of the array, assigning it to the scalar variable $fruit. The print statement within the loop block prints the value of $fruit to the screen.

You can also use the foreach loop to iterate over a range of numbers. The .. range operator is used to create a range of numbers, and the loop variable takes on each value in the range during each iteration of the loop. Here's an example:

foreach my $num (1..10) {
    print "$num\n";
}

In this example, the foreach loop iterates over the range of numbers from 1 to 10, assigning each value to the scalar variable $num. The print statement within the loop block prints the value of $num to the screen.

You can use any expression that returns a list as the list to iterate over in a foreach loop. For example, you can use the split function to split a string into a list of substrings, and iterate over the substrings. Here's an example:

my $str = "foo,bar,baz";
foreach my $word (split /,/, $str) {
    print "$word\n";
}

In this example, the split function splits the string $str into a list of substrings, using the comma , as the delimiter. The foreach loop iterates over the substrings, assigning each substring to the scalar variable $word. The print statement within the loop block prints the value of $word to the screen.