Add /Replace New values to Hash in Perl

How to Adding Elements to a Hash structure?
How to replace the same key with different values using Hash?


Accessing an element in a hash structure is similar to that from an array, except we replace square brackets with curly ones and instead of an index, the key is used.

print $name{Tom};

In the above example Tom is equivalent to 'Tom'.To add a new scalar value use the following code.

$name{Tom} = value;

Example :

#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom' => 26, 'Peter' => 51, 'Jones' => 23);
print "Before Adding:<br>";
# In a loop print the hash
while (($key, $value) = each(%name))
print $key.", ".$value."<br/>";
# Add a key "Sam" with value "31" is added
$name{Sam} = 31;
# Add a key "Peter" with value "90" is added
$name{Peter} = 90;
print "After Adding:<br>";
#In a loop print the new hash
while (($key, $value) = each(%name))
print $key.", ".$value."<br/>";
Result :

Before Adding values:
Jones, 23
Peter, 51
Tom, 26
After Adding values:
Jones, 23
Peter, 90
Sam, 31
Tom, 26

In the above example we are adding the same key ie., "Peter" with a different value ie., "90", so the key is replaced with the new value using a hash structure.

Ask Questions

Ask Question