Contents


On-line Guides
All Guides
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems

How To Guides
General How To Guides
JavaScript How To
HTML How To
Problem Solutions

 

 

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

4.7 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.




 
 
  Published under the terms of the GNU General Public License Design by Interspire