Perl loop examples - The Perl foreach, for, while, and until loops

Perl loop FAQ: Can you share some "Perl loop" examples (Perl for loops, foreach loops, and Perl arrays)?

I've written a variety of "Perl loop" stories before, but I've never shown all the different Perl loop operators in one place before. In this Perl tutorial I'll try to provide a summary of the different Perl loop constructs.

A simple Perl array

Before showing any Perl loop examples, we'll need an array to work with. Here's a simple Perl array that contains five strings:

@pizzas = qw(cheese pepperoni veggie sausage works);

I'll refer to this array in all of the following examples.

Perl foreach loop

When I think about Perl loops, I probably use the Perl foreach loop more than any other type of loop, so I'll show that syntax here first:

foreach $elem (@pizzas) {
  print "$elem\n";
}

As you can see, you just put the array name in between the parentheses (@pizzas), and then specify the name you want each element to be called (in this case, $elem), so you can refer to that name inside the curly braces.

In the foreach example shown, the foreach loop starts with the first element in the @pizzas array, makes that element available to you via the $elem variable, and then lets you do whatever you want with that element inside the block portion of the loop (i.e., inside the curly braces). When your code in the block finishes, the foreach loop assigns the next array element to your $elem variable, and the whole process continues again.

Update: You learn something new every day. The Perl "foreach" operator is actually a synonym for the Perl "for" operator, so you can use either keyword in the foreach loop example just shown, and the for loop examples about to be shown.

Perl for loop syntax

The Perl for loop is similar to the foreach loop, but instead of assigning a name to each element, you just refer to the current element with the special $_ variable, like this:

for (@foo)
{
  print $_, "\n";;
}

While this seems easier, I prefer to the Perl foreach loop to the for loop (see "Perl best practice - prefer Perl foreach loop to for loop"), especially if you don't use Perl every day. I think the foreach loop is easier to read/maintain.

Perl for loop - other syntax

There's also another way to use a Perl for loop, and this is the one area where I like the for loop syntax:

for ($i=0; $i<5; $i++)
{
  print "i = $i\n";
}

When using this type of Perl for loop, you are often not working with an array, but are working in a loop for some other reason. Any other time you are working with a Perl array, I prefer the earlier foreach or for loop syntax.

Perl while loop syntax

You can create a simple Perl while loop using the following syntax:

$counter = 0;
while ($counter < 11) {
  print "counter = $counter\n";
  $counter++;
}

print "The counter reached 10.\n"; 

This example is similar to the previous for loop example, where you have a counter, and you're incrementing that counter while doing something else in the loop. In this case I'm just printing a string, but in your code you'll be doing something more complex.

The Perl while loop is used more often when iterating over a Perl hash. For instance, in the following example, I first create a simple Perl hash, and then I iterate over the hash with a while loop:

# create a simple perl hash
$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;

# loop over the hash with a perl while loop
while (($key, $value) = each (%prices))
{
  # do whatever you want with $key and $value here ...
  $value = $prices{$key};
  print "  $key costs $value\n";
}

In this case I get the current key and value from the hash using the each function, but there are several ways this can be done.

Perl until loop syntax

The Perl until loop works like while loop, but they are essentially opposite of each other. Where the Perl while loop operator will run this loop forever:

while ('true')
{
  # do stuff here
}

the Perl until loop will never run this loop:

until ('true')
{
  # do stuff here
}

The until loop never runs that block of code because the loop test condition is immediately true. So, where the while loop runs a loop as long as a condition is true, the Perl until loop runs until a condition is true.

A cool thing about a Perl until loop (or while loop) is that you can run them on the right-hand side of an equation as an expression modifier, like this:

print "Yo\n" until $i++ > 3;

That code will result in the following output:

Yo
Yo
Yo
Yo

Perl loop syntax - summary

I hope this Perl loop syntax summary has been helpful. As a quick review, in this article we looked at the syntax for the following Perl loop constructs:

  • Perl for loop
  • Perl foreach loop
  • Perl while loop
  • Perl until loop

More Perl loop tutorials

As mentioned, I've written many more-detailed tutorials about Perl loop constructs, and this tutorial is meant as more of a broad summary/review. Here are a few links to some of the more-detailed Perl loop tutorials I've written: