Wednesday, January 9, 2008

Printing an Associative Array

The each() function returns key, value pairs of an associative array one-by-one in a list. This is called iterating over the elements of the array. Iteration is a synonym for looping. So, you also could say that the each() function starts at the beginning of an array and loops through each element until the end of the array is reached. This ability lets you work with key, value pairs in a quick easy manner.

The each() function does not loop by itself. It needs a little help from some Perl control statements. For this example, we'll use the while loop to print an associative array. The while (CONDITION) {} control statement continues to execute any program code surrounded by the curly braces until the CONDITION turns false, assoc.pl.

%array = ( "100", "Green", "200", "Orange");



while (($key, $value) = each(%array)) {

print("$key = $value\n");

}

This program prints:

100 = Green

200 = Orange

The each() function returns false when the end of the array is reached. Therefore, you can use it as the basis of the while's condition. When the end of the array is reached, the program continues execution after the closing curly brace. In this example, the program simply ends.

1 comment:

Anonymous said...

Hello


Use http://www.BuySellDirect.net as a FREE home based ebay to make money at home. It is 100% free.


Why not, you can use http://www.BuySellDirect.net FREE service to make a second income.