Beginning Perl Control Structures Tutorial on Foreach

Learn how to step through an array in Perl with foreach

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:

 @myNames = ('Larry', 'Curly', 'Moe');
 foreach (@myNames) {
 	print $_;
 } 

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

 LarryCurlyMoe 

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.

 @myNames = ('Larry', 'Curly', 'Moe');
 print "Who's on the list:\n"; foreach (@myNames) {
 	print $_ . "\n";
 } 

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

 Who's on the list:
 Larry
 Curly
 Moe 

A Cleaner Foreach Loop

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

 @myNames = ('Larry', 'Curly', 'Moe');
 foreach (@myNames) {
 	print $_;
 } 

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 highly readable code or if your foreach loop is complex, you might be better off assigning a scalar as your iterator.

 @myNames = ('Larry', 'Curly', 'Moe');
 foreach $name (@myNames) {
 	print $name;
 } 

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.