Perl hash - delete example

Perl hash delete FAQ: How do I delete an element (a key/value pair) from a Perl hash? Also, how do I delete multiple Perl hash elements at one time?

A Perl hash delete example - Delete an element by hash key

To delete a Perl hash element, use the Perl "delete" function. The general syntax of the Perl delete function looks like this:

delete($hash{$key});

Here's the source code for a simple Perl script that shows how to add elements to a Perl hash, and then shows how to delete each Perl hash element by specifying the hash key with the Perl delete function:

# create a simple perl hash
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;

# print all the elements in the hash
print "before:\n";
print %prices;

# delete the hash element with the 'pizza' key
print "\n\nremove pizza:\n";
delete($prices{'pizza'});
print %prices;

# delete the hash element with the 'sandwich' key
print "\n\nremove sandwich:\n";
delete($prices{'sandwich'});
print %prices;

# delete the hash element with the 'coke' key
print "\n\nremove coke:\n";
delete($prices{'coke'});
print %prices;

If you run that Perl script, you'll see that each hash element is deleted from the Perl hash.

Delete multiple Perl hash elements at one time

While that example shows how to delete one Perl hash element at a time, sometimes you may want to delete multiple Perl hash elements with one command. To delete multiple Perl hash elements (key and value) at one time, just pass the Perl delete function the hash keys in an array, like this:

delete @hash{key1, key2, ...};

Here's a short Perl script that demonstrates this:

# create a simple perl hash
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;

# print the contents of the perl hash before we do anything
print "before:\n";
print %prices;

# delete the 'coke' and 'pizza' hash elements by
# specifying their keys in an array
print "\n\nremove coke and pizza:\n";
delete @prices{'coke', 'pizza'};

# print the remaining elements of the perl hash.
# (at this point it just contains the 'sandwich' element)
print %prices;

Myself, I find this syntax very hard to remember:

delete @prices{'coke', 'pizza'};

and that's one reason I have this tutorial out here.

Perl hash delete - summary

I hope this "Perl hash delete" tutorial has been helpful. As you've seen here, the first trick in deleting an element from a Perl hash is knowing to use the Perl delete function. The second trick is then knowing the proper syntax, in particular the syntax for deleting multiple hash elements at one time.

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:

More advanced Perl hash tutorials:

The hash in Perl - hash sorting tutorials: