Perl - Foreach Loop
The Perl foreach loop is used to loop through each element of a list. In each iteration of the loop, current list element can be accessed using user-defined variable if provided. If the variable is not provided, the current list element can be accessed using topic variable $_.
Syntax
#method 1 foreach variable (list){ statements; } #method 2 foreach (list){ statements; }
Flow Diagram:
Foreach loop over an array
In the example below, the foreach loop is used to access all elements of a given array.
@numbers = (10, 20, 30, 40, 50); foreach $i (@numbers) { print "i = $i\n"; }
The output of the above code will be:
i = 10 i = 20 i = 30 i = 40 i = 50
Foreach loop over a range
In this example, the foreach loop is used over a range. Elements of the range is accessed using topic variable $_.
foreach (1..5) { print "\$_ = $_\n"; }
The output of the above code will be:
$_ = 1 $_ = 2 $_ = 3 $_ = 4 $_ = 5
Foreach loop over a Hash
Consider one more example where the foreach loop is used to access all key/value pairs of a given hash.
%colors = (1 => "Red", 2 => "Blue", 3 => "Green", 4 => "Black", 5 => "White"); foreach $i (keys %colors) { print "$i : $colors{$i} \n"; }
The output of the above code will be:
1 : Red 2 : Blue 5 : White 4 : Black 3 : Green