1. Home
  2. Computing & Technology
  3. Perl

Perl values() function - Quick Tutorial

How to use the values() function

From About.com

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

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl values function reference - learn how to use Perl's values() function in this quick tutorial.

©2008 About.com, a part of The New York Times Company.

All rights reserved.