foreach - Beginning Perl Tutorial, Control Structures

Looping through an array in Perl with foreach

Next: A cleaner foreach loop

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. Rather than using a scaler as that iterator (like the for loop), foreach uses the array itself.

 @myNames = ('Larry', 'Curly', 'Moe');
 foreach (@myNames) {
 	print $_;
 } 
You'll see that this gives us the same output as printing the array @myNames in it's entirety:
 LarryCurlyMoe 
If all we wanted was to dump out the contents of our list, we could have just printed it. Lets 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 creates a cleaner output by printing a newline after each item in the list.
 Who's on the list:
 Larry
 Curly
 Moe 
Next: A cleaner foreach loop

In the previous example, you'll notice we 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 isn't always the best solution. If you're aiming for highly readable code, or if your foreach loop contains a lot of complexity, you might be better off assigning a scalar as your iterator.
 @myNames = ('Larry', 'Curly', 'Moe');
 foreach $name (@myNames) {
 	print $name;
 } 
You can see there are only 2 differences. We've added the scalar $name between the foreach and the list, and we've replaced the default scalar with it inside the loop. The output is exactly the same, but the code itself is slightly clearer.
  1. A foreach loop is a Perl control structure.
  2. It is used to step through each element of an array.
Previous: Looping through an array in Perl with foreach