FreeKB - Hash in Perl - Getting Started
Hash in Perl - Getting Started

Home > Search

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

Key Value
Name Jeremy
ID 123456
Occupation Engineer


Generally speaking, there are two approaches to create the hash key:value pair. You either create an empty hash and then append values (this is the much more common approach) or you define the hash and the key:value pairs.


Start with a hash that contains values

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

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


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 print the contents of the entire hash.

print %hash;


Which 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};


Loop through keys / values

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

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


Which will print each key.



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

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


Which will print each value.

Jeremy Canfield


Or like this.

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


Will print the values.

Jeremy Canfield



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 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}};


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 31b01 in the box below so that we can be sure you are a human.