The for and foreach statements in Perl are actually identical. They can be used interchangeably in any context. Depending on what job is being performed, however, one usually make more sense than the other.
Just to make things more confusing, there are two ways that the for/foreach statement can be used. One way is exactly like C's 3-argument for statement. For instance:
@disks = ("/data1","/data2","/usr","/home"); for ($i=0; $i <= $#disks; ++$i) { print $disks[$i],"\n"; }
However, once you understand Perl's built-in ways of iterating over an array's elements, you will almost never need to use the 3-argument for statement.
Perl's one-argument foreach statement is similar to the foreach statement in the C Shell. Given an array argument, the foreach statement will iteratively return that array's elements. This contrasts with the destructive traversal demonstrated before with the while and shift statements.
The code fragment we just saw can be rewritten as:
@disks = ("/data1","/data2","/usr","/home"); foreach(@disks) { print $_,"\n"; }
This construct is much more elegant and does not (necessarily) destroy the contents of @disks.
An subtle but important point to note is that, in the fragment above, $_ is really a pointer into the array, not simply a copy of a value. If the code in the loop modifies the $_, the array is changed.