Hash is also called associate arrays. It stores keys and values.

Also called a Hashtable or dictionary in other programming languages.

The elements or pairs stored in the hash are unordered.

Each key and value contains scalar types such as Strings or numbers.

How to create a hash variable in Perl?

Variable creation contains two parts separated by =. The left part contains the Variable prefixed with % and name, Right part contains a pair of items enclosed in (). Each pair of elements contains a key and value of scalar values, separated by the fat comma operator =>.

my % employee = ("id" => "11",
    "name" => "john",
    "dept" => "sales",
    "salary" => "2000",

);

How to access hash values in Perl?

Hash values can be retrieved using the below syntax

# key can be enclosed in single or double quotes.
$hashvariable{key};

Here is an example

my %employee = ("id" => "11",
    "name" => "john",
    "dept" => "sales",
    "salary" => "2000",

);
print %employee{'id'};
print %employee{"name"};

Add an element to Hash in Perl

key and value pair added to hash using the below syntax

@variable{"key"} = "value";

Here is an example

my %employee = ("id" => "11",
    "name" => "john",
    "dept" => "sales",
    "salary" => "2000",

);
@employee{"role"} = "admin";
foreach my $key (keys %employee)
{
  $value = $employee{$key};
  print "  $key - $value\n";
}

Iterate key and values in a hash

my %employee = ("id" => "11",
    "name" => "john",
    "dept" => "sales",
    "salary" => "2000",

);
foreach my $key (keys %employee)
{
  $value = $employee{$key};
  print "  $key - $value\n";
}