Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
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
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

[ < ] [ > ]   [ << ] [ 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