Beginning Perl Control Structures Tutorial on Foreach

Learn how to step through an array in Perl with foreach

woman types on laptop keyboard
dm909/Getty Images

The foreach loop is a control structure that's tailor-made to process Perl lists and hashes. Just like the for loop, foreach steps through each element of an array using an iterator.

How to Step Through an Array in Perl With Foreach

Rather than using a scaler as an iterator, foreach uses the array itself. For example:

You see that this gives the same output as printing the array @myNames in its entirety:

If all you want is to dump out the contents of the list, you could just print it. In that case, use the foreach loop to make the output a bit more readable.

You'll see that this code creates cleaner output by printing a new line after each item in the list.

A Cleaner Foreach Loop

The previous example used $_ to print each element of the list.

Using this default implied scalar ($_) makes for shorter code and less typing, but it isn't always the best solution. If you're aiming for a highly readable code or if your foreach loop is complex, you might be better off assigning a scalar as your iterator.

There are only two differences: the scalar $name between the foreach and the list and the replacement of the default scalar with it inside the loop. The output is exactly the same, but the code is slightly cleaner. Keep in mind:

  • A foreach loop is a Perl control structure.
  • It is used to step through each element of an array.