Perl

  1. Home
  2. Computing & Technology
  3. Perl

foreach - Beginning Perl Tutorial, Control Structures

A cleaner foreach loop

From About.com

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

Explore Perl

About.com Special Features

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Looping through an array in Perl with foreach

©2009 About.com, a part of The New York Times Company.

All rights reserved.