Node:The foreach Structure, Previous:The for Structure, Up:Control Structures

The foreach Structure

The foreach control structure is the most interesting in this chapter. It is specifically designed for processing of Perl's native data types.

The foreach structure takes a scalar, a list and a block, and executes the block of code, setting the scalar to each value in the list, one at a time. Consider an example:

     use strict;
     my @collection = qw/hat shoes shirts shorts/;
     foreach my $item (@collection) {
         print "$item\n";

This will print out each item in collection on a line by itself. Note that you are permitted to declare the scalar variable right with the foreach. When you do this, the variable lives only as long as the foreach does.

You will find foreach to be one of the most useful looping structures in Perl. Any time you need to do something to each element in the list, chances are, using a foreach is the best choice.