1. Perl
  2. builtin functions
  3. here

each function - processes all keys and values in the hash

You can use the each function to get a key/value pair of hash in order. With repeated use, you can get all the keys and values.

# Get a hash key/value pair
my ($key, $value) = each %hash;

You can get all (key, value) pairs in order by using each repeatedly. The order of the (key, value) pairs to get is indefinite.

# Get (key, value) pairs in order
my %age = (Ken => 19, Mike => 34);
while (my ($name, $age) = each %age) {

while statement is used to retrieve the key/name pairs in order.

I think it's rare to use each function in practice. The same process can be done using keys function, which is more flexible. In Perl today, the keys function is optimized, so in terms of performance, the keys function is not slower than the each function.

You can also use values function to get only all the values of the hash.

Example program

This is an example that processes all the elements of the hash using the each function.

use strict;
use warnings;

# Student math scores
my %math_scores = (
  Taro => 89,
  Naoko => 54,
  Kenji => 54,

# Output all elements of the hash using the each function.
print "1: All elements of the hash Print using the each function\n";
while (my ($key, $value) = each %math_scores) {
  print "%math_scores{$key} = " . $math_scores{$key} . "\n";
print "\n";


# 1: Output using all elements of the hash each function
%math_scores{Kenji} = 54
%math_scores{Taro} = 89
%math_scores{Naoko} = 54

Related Informatrion