Perl Foreach -- Looping With Foreach in Perl

The foreach keyword is probably the easiest and most often used looping construct in Perl. Use it for looping through the items in an array.

my @items = ("apple", "orange", "banana");

foreach my $item(@items) {
    print "$item\n";
}




apple
orange
banana




Here we're creating an array and initializing it with three strings, then displaying the strings by looping through the array with foreach and printing the strings with print. foreach sets $item (or whatever variable you specify) to each of the array elements in turn.

In fact, if you don't declare a variable for foreach to place the array items in one by one, it uses the default $_ variable. So the following program is exactly equivalent to the one above.

my @items = ("apple", "orange", "banana");

foreach(@items) {
    print "$_\n";
}






Modifying Array Elements in Perl With Foreach



If you modify the variable that you tell foreach to place the array items in, the actual elements of the original array are modified.


my @items = ("apple", "orange", "banana");

# Modify the items (this is a trivial example but
# of course it could easily do something a lot
# more complex and useful).
foreach my $item(@items) {
    $item = 'FRUIT: ' . $item;
}

# Display the array.
foreach my $item(@items) {
    print "$item\n";
}




FRUIT: apple
FRUIT: orange
FRUIT: banana




Surprising eh? But very useful.

Using Foreach with Regular Expressions in Perl



Of course, regular expressions also use the $_ variable by default. So if your purpose in looping through an array is to match certain items and take some action, or to modify certain items with a regular expression, you can miss out the loop variable altogether. Personally I prefer to include it anyway, for clarity. But here's how you'd write code without it:

my @items = ("apple", "orange", "banana");

# Both foreach and the default regular expression quotes //
# use the $_ variable implicitly if no other is specified.
foreach (@items) {
    /orange/ and print "Found one!";
}




Found one!




Another Way of Looping Through Arrays In Perl



Sometimes it's nice to just use the C-style for way of looping in Perl (or maybe I just think that because I learned C before Perl!). This style draws more attention to the numerical index of the array item you're dealing with. Of course you could achieve the same thing using a foreach by creating a counter variable before the loop and incrementing it on every iteration, but what the hell ....

In this code, notice we've found the length of the array just by using it in a scalar context. To reduce potential confusion, we could equally well have written $i < scalar(@items) instead, using the scalar keyword for clarity.

my @items = ("apple", "orange", "banana");

for(my $i=0; $i < @items; $i++) {
    print $items[$i], "\n";
}




apple
orange
banana