1. Technology
Send to a Friend via Email

Your suggestion is on its way!

An email with a link to:

http://perl.about.com/od/perltutorials/a/foreachloop.htm

was emailed to:

Thanks for sharing About.com with others!

foreach - Beginning Perl Tutorial, Control Structures

Looping through an array in Perl with foreach

By

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
  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. Looping through an array in Perl with foreach

©2014 About.com. All rights reserved.