How to create and use a hash in Perl

Home > Search > How-to

A hash, or more technically an associative array, assigns a key to a value. For example, let's say you have the following key:value pairs.

Key Value
Name Jeremy Canfield
ID 123456
Occupation Engineer


In this example, a variable named %hash is created, and the %hash variable contains the key:value pairs.

my %hash = ('name' => Jeremy, 'id' => 123456, 'occupation' => Engineer);


You can then print the value of a hash item. For example, the following will print the value of the name key, which is "Jeremy".

print $hash{name};


Start with an empty hash

Some Perl scripts will begin by creating a hash that does not contain any key:value pairs.

my %hash = ();


Then, somewhere in the script key:value pairs will be created. In this example, a key called "name" is created with a value of "Jeremy" and another key called "occupation" with a value of "engineer".

$hash{name}       = ("Jeremy");
$hash{occupation} = ("Engineer");


You can then print the values associated with a hash key.

print $hash{name};
print $hash{id};
print $hash{occupation};



You can create a variable for one or more of the key:value pairs.

$username = $hash{name};
$userid = $hash{id};
$useroccupation = $hash{occupation};


You can then print the value's associated with each key:value pair.

print $username;
print $userid;
print $useroccupation;


Loop through keys

You will usually want to loop through the hash. The following foreach loop will print the keys.

foreach $keys (keys %hash) {
    print $keys;


The following foreach loop will print the value associated with each key.

foreach $keys (keys %hash) {
    print $hash{$keys};


Loop through values

The following foreach loop with print the values.

foreach $values (values %hash) {
    print $values;


This will print the values.

Jeremy Canfield


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.