This tutorial explains about foreach loop in Perl with examples

perl foreach loop example

foreach loop iterates a list of elements, Syntax:

foreach variable (arrayvariable){

}

variable: It stores each iterated element arrayvariable: An array variable

my @numbers = (1,2,3,4,5,6);

# foreach loop example
print("For-each Loop:\n");
foreach $number (@numbers) 
{ 
    print ("$number\n");
} 

perl for each loop in the subroutine

For example, This is an example of printing an array using a subroutine

sub iterateNumbers {    
    foreach my $i (@_) {
       print "a-$i\n";
    }
}

@numbers = (1,2,3,4);
iterateNumbers(@numbers);

Another example is, Modify the array inside a foreach loop.

sub iterateNumbers {    
    foreach my $i (@_) {
       $i= "a-$i\n";
    }
}

@numbers = (1,2,3,4);
iterateNumbers(@numbers);
print "@numbers"

Inside foreach loop, An iterated element($i) still references in an array.

In Subroutine, @_ is a reference to a List.