values HASH
Perl's
values() function is used to iterate (loop) through the the values of a
HASH. The values are returned as a list (array).
%contact = ('name' => 'Bob', 'phone' => '111-111-1111');
foreach $value (values %contact) {
print "$value\n";
}
In the above example, we start with a simple
hash of our contact Bob and his phone number. The
values function takes this regular hash as input, and is couched in a
foreach loop. Here is the each function standing on it's own:
$value (values %contact)
Every time the
values function is called, it grabs a value out of the hash and puts it in the
$value string. When couched in the
foreach statement it will loop through each element of the hash and pass the values off to the print statement. The output of the program will be:
Bob
111-111-1111
There are a couple of things to keep in mind when using the
keys function. Because of the way Perl works with hashes, the elements will be returned in random order. Also, the
keys function does not remove the elements from the hash - the hash is unaffected by the looping process.
More Perl Quick Tips