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

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

  




 

 

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

5.4.2 Each

The each function is one that you will find particularly useful when you need to go through each element in the hash. The each function returns each key-value pair from the hash one by one as a list of two elements. You can use this function to run a while across the hash:

use strict; my %table = qw/schmoe joe smith john simpson bart/; my($key, $value); # @cc{Declare two variables at once} while ( ($key, $value) = each(%table) ) { # @cc{Do some processing on @scalar{$key} and @scalar{$value}} }

This while terminates because each returns undef when all the pairs have been exhausted. However, be careful. Any change in the hash made will "reset" the each function for that hash.

So, if you need to loop and change values in the hash, use the following foreach across the keys:

use strict; my %table = qw/schmoe joe smith john simpson bart/; foreach my $key (keys %table) { # Do some processing on $key and $table{$key} }




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