Perl uses a function delete() to remove an element from the hash structure.To remove all the elements from an array fast, one can use the following statements.
%name = (); # defining a hash
undef %name; # Removing a hash
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom',26,'Peter',51,'Jones',23,'John',43);
print "Before Deleting::n";
print "<br>";
# In a loop print the hash
while (($key, $value) = each(%name))
{
print $key.", ".$value."<br/>";
}
# Delete a key "Peter"
delete $name{Peter};
# Delete a key "John"
delete $name{John};
print "After Deleting::n";
print "<br>";
# In a loop print the new hash
while (($key, $value) = each(%name))
{
print $key.", ".$value."<br/>";
}
Result :
Before Deleting::
John, 43
Jones, 23
Peter, 51
Tom, 26
After Deleting::
Jones, 23
Tom, 26
In the above example we have declared a hash called "name", just by deleting the keys "Peter", "John" alone, Perl automatically deletes it.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom' => 26, 'Peter' => 51, 'Jones' => 23);
@store = delete $name{'Peter'};
print "Deleted value of the key Peter:: ", @store ,"n";
Result :
Deleted value of the key Peter:: 51
Only hash structure provides an option to store the value of an hash key just deleted in an array, in the above example the value of the deleted key "Peter" is stored in the array "@store".
Removing a Hash completely:
Using the delete() function an entire hash elements can also be deleted.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom',26,'Peter',51,'Jones', 23, 'John', 43);
print "Elements of hash before deleting";
print "<br>";
while (($key, $value) = each(%name))
{
print $key.", ".$value.""<br/>";
}
foreach $key (keys %name)
{
delete $name{$key};
}
print "Values of Hash after deletingn";
print "<br>";
print scalar grep defined($_),values %name;
Result :
Elements of hash before deleting
John, 43
Jones, 23
Peter, 51
Tom, 26
Values of Hash after deleting
0
In the above example first all the elements of hash is printed, then using the delete function in a loop all the hash elements are removed,then to check it we used the grep() function to check the values of hash.