FreeKB - How to create and use a hash in Perl
How to create and use a hash in Perl

Home > Search > How-to

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

Key Value
Name Jeremy
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 print the contents of the entire hash.

print %hash;


print %hash will print all of the keys and values in the hash, like this.

Name Jeremy Canfield ID 123456 Occupation Engineer


Or, you can print the value of a key. For example, the following will print the value "Jeremy" in the "name" key.

print $hash{name};


Start with an empty hash

Following are both valid examples of how to create an empty hash (does not contain any key value pairs).

my %hash;
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.

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


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

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



Each hash key will contain a single value, which is to say that a hash key cannot contain multiple values. For example, if you were to do something like this,  $hash{name} will only contain a value of Winston.

$hash{name} = "Jeremy";
$hash{name} = "Winston";


A solution to this change is to create an array that contains multiple values. In this example, the @{$hash{name}} array will contain both Jeremy and Winston.

push ( @{$hash{name}}, Jeremy );
push ( @{$hash{name}}, Winston );


You can then use a foreach loop to print all of the values in the array.

foreach my $key (keys %hash) {
    print @{$hash{$key}};


Loop through keys

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

foreach (keys %hash) {
    print $_;


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

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


Loop through values

The following foreach loop with print the values.

foreach (values %hash) {
    print $_;


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.