By Alvin Alexander. Last updated: June 4, 2016
Perl FAQ: How do I remove an item from a hash?
Answer: Use the Perl delete function.
The general syntax you need to use is shown here:
delete($hash_name{$key_name});
If you'd like more details and examples, read on...
Perl hash - remove/delete element example
Here's a complete example where I show both how to create and print a Perl hash, and then show how to remove elements from the hash using the Perl delete function:
#!/usr/bin/perl
#-------------------------------
# add items to the "prices" hash
#-------------------------------
$prices{"pizza"} = 12.00;
$prices{"coke"} = 1.25;
$prices{"sandwich"} = 3.00;
#---------------
# print the hash
#---------------
print "\nbefore:\n";
foreach $key (keys %prices)
{
print " $key costs $prices{$key}\n";
}
#------------------------------
# remove the coke from the hash
#------------------------------
delete($prices{"coke"});
#---------------
# print the hash
#---------------
print "\nafter:\n";
foreach $key (keys %prices)
{
print " $key costs $prices{$key}\n";
}
Output from the sample program
Here's what the output from this sample program looks like:
before: sandwich costs 3 pizza costs 12 coke costs 1.25 after: sandwich costs 3 pizza costs 12
As you can see from the output, the coke element has been removed from the hash.
Related Perl hash tutorials
I hope you found this short Perl hash tutorial helpful. We have many more Perl hash tutorials on this site, including the following:
Getting started Perl hash tutorials:
- Perl hash introduction/tutorial
- Perl foreach and while: how to loop over the elements in a Perl hash
- Perl hash add - How to add an element to a Perl hash
- How to print each element in a Perl hash
More advanced Perl hash tutorials:
The hash in Perl - hash sorting tutorials:

