|
Perl Question: How do I remove an item from a hash?
Answer: Use the 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...
A complete 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 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.
|