Assignment into a hash variable

To create a hash with all of its key-value pairs, you can use one of several equivalent ways:

%hash = ("key1" => "val1",
         "key2" => "val2",
         "key3" => "val3");

%hash = ("key1" => "val1", "key2" => "val2", "key3" => "val3");

%hash = ("key1", "val1", "key2", "val2", "key3", "val3");
Actually, the => operator is just a synonym for a comma. Its sole role here is to increase readability.

Therefore, in all the above examples, we write data to be assigned to the hash variable as a list. Each pair of elements in the list (which should always have an even number of elements) defines a key and its corresponding value.

Hashes are internally stored in a way that will optimize retrieval of values by their keys. Therefore, the order in which the elements were assigned to the hash is irrelevant.

For example, if you assign a hash variable back to an array variable, the order of the key value pairs might be different than the one used while defining the hash:

use strict;
use warnings;

my %hash = ("a", "b", "x", "y", "m", "n");

my @list = %hash;

print "@list\n";
This might result in:
x y a b m n

Creating an empty hash

To create a hash with no entries, assign an empty list into it, e.g.:

%myEmptyHash = ();

Table of Contents.