foreach $day (@life) {
   do &stuff($day);
}
die "No more days left!";

Foreach loops over a list, setting $_ (by default; $day above) to the current list element. Like for, only even more convenient.
A foreach loop is available implictly in many programming languages (including Perl, LPC and C#) and created using consutrcts such as for loops in other languages.

Generally speaking, a foreach loop iterates over each member of an array or list, performing an operation or series of operations on each element in this data structure. Here are some examples -

Perl -

foreach (@listofStrings) {
print $_;
}
die "Done.";

Note that Perl takes every element of the list and puts it into the special variable $_.

LPC -

string *carp = ({"foo", "bar"});
foreach ( object koi in carp ) {
write(koi);
}

LPC demands that you specify a variable to put each element of the array into. In the above example, the object variable koi only has a scope of the foreach loop.

The benefits of this construct should be fairly clear. It can be used to perform an action on every part of a linear array or list, and can be used to perform an action on every member of an associative array by foreach()ing the keys to this structure.

In Perl, as There Is More Than One Way To Do It, foreach is often (er, almost always) used in lieu of a regular for loop. Added to the fact that the "each" can be omitted and combined with the .. operator, this allows for really short friendly loops, such as the following:

$FACTORIAL = 5;
$answer = 1;
for (1 .. $FACTORIAL) {
  $answer *= $_;
}
print "The answer is $answer.\n";

The only disadvantage to doing this is that you'll probably attempt to do it the same way in another language at some point.

As Noung and Eevee's writeups show, a foreach command makes for short, clear code. You perform some command block for each value in a given list or array. Is foreach really the same as for (or is one of them plain "better")? The names are confusing, and several people (or programming languages) seem not to make the distinction. foreach is distinct from for in that it requires a list (or whatever) of all the values to be used. For long loops, this means a lot of memory. Also, you need to know before you start the loop what values you'll want to go through (in other words, the values the loop variable is assigned cannot depend on calculations performed in the loop itself).

This makes foreach useful for a lot of scripting, where you not only know the values ahead of time, you probably anyway got them as a complete list (e.g. for a glob, or previous text processing. When what you're doing is more computational, what you want is a for loop.

Log in or register to write something here or to contact authors.