Wednesday, January 9, 2008

Checking the Existence of an Element

You can use the defined() function to check if an array element exists before you assign a value to it. This ability is very handy if you are reading values from a disk file and don't want to overlay values already in memory. For instance, suppose you have a disk file of Jazz Artist addresses and you would like to know if any of them are duplicates. You check for duplicates by reading the information one address at a time and assigning the address to an associative array using the Jazz Artist name as the key value. If the Jazz Artist name already exists as a key value, then that address should be flagged for follow up.

Because we haven't talked about disk files yet, we'll need to emulate a disk file with an associative array. And, instead of using Jazz Artist's address, we'll use Jazz Artist number and Jazz Artist name pairs. First, we see what happens when an associative array is created and two values have the same keys, element1.pl.

createPair("100",  "Miles Davis");

createPair("200", "Keith Jarrett");

createPair("100", "John Coltrane");



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

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

};



sub createPair{

my($key, $value) = @_ ;



$array{$key} = $value;

};

This program prints:

100, John Coltrane

200, Keith Jarrett

This example takes advantages of the global nature of variables. Even though the %array element is set in the createPair() function, the array is still accessible by the main program. Notice that the first key, value pair (100 and Miles Davis) are overwritten when the third key, value pair is encountered. You can see that it is a good idea to be able to determine when an associative array element is already defined so that duplicate entries can be handled. The next program does this, element2.pl.

createPair("100",  "Miles Davis");

createPair("200", "Keith Jarrett");

createPair("100", "John Coltrane");

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

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

};



sub createPair{

my($key, $value) = @_ ;



while (defined($array{$key})) {

$key++;

}



$array{$key} = $value;

};

This program prints:

100, Miles Davis

101, John Coltrane

200, Keith Jarrett

You can see that the number for John Coltrane has been changed to 101.

No comments: