(This is the official perlfaq answer , minus any subsequent changes)
There are several ways to handle the entire hash. You can get a list of keys , then go through each key or take one key-value pair at a time.
To pass all the keys, use the function. This extracts all the hash keys and returns them to your list. Then you can get the value through a specific key that you are processing:
foreach my $key ( keys %hash ) { my $value = $hash{$key} ... }
Once you have a list of keys, you can process this list before processing the hash elements. For example, you can sort keys so that you can process them in lexical order:
foreach my $key ( sort keys %hash ) { my $value = $hash{$key} ... }
Or you can only process certain items. If you want to deal only with keys starting with text: you can only choose those that use grep:
foreach my $key ( grep /^text:/, keys %hash ) { my $value = $hash{$key} ... }
If the hash is very large, you may not need to create a long list of keys. To save some memory, you can capture one key-value pair at the same time using each () , which returns a pair that you have not seen
while( my( $key, $value ) = each( %hash ) ) { ... }
Each operator returns pairs in a clearly random order, so if ordering is important for you, you will have to stick with the key method.
each () operator can be a little more complicated. You cannot add or remove hash keys while it is in use without missing or processing multiple pairs after Perl internally rephrases all elements. In addition, the hash has only one iterator, so if you use keys , values or each on the same hash, you can reset the iterator and ruin your processing. See each entry in perlfunc for more details .