Problem
You want to remove an entry from a hash so that it doesn’t showup with keys
, values
, oreach
. If you were using a hash to associatesalaries with employees, and an employee resigned, you’d wantto remove their entry from the hash.
Solution
Use the delete
function:
# remove $KEY and its value from %HASHdelete($HASH{$KEY});
Discussion
Sometimes people mistakenly try to use undef
toremove an entry from a hash. undef
$hash{$key}
and $hash{$key}
=
undef
both make%hash
have an entry with key$key
and value undef
.
The delete
function is the only way to remove aspecific entry from a hash. Once you’ve deleted a key, it nolonger shows up in a keys
list or aneach
iteration, and exists
willreturn false for that key.
This demonstrates the difference between undef
anddelete
:
# %food_color as per Introductionsub print_foods { my @foods = keys %food_color; my $food; print "Keys: @foods\n"; print "Values: "; foreach $food (@foods) { my $color = $food_color{$food}; if (defined $color) { print "$color "; } else { print "(undef) "; } } print "\n";}print "Initially:\n";print_foods();print "\nWith Banana undef\n";undef $food_color{"Banana"};print_foods();print "\nWith Banana deleted\n";delete $food_color{"Banana"};print_foods();
Initially:
Keys: Banana Apple Carrot Lemon
Values: yellow red orange yellow
With Banana undef
Keys: Banana Apple Carrot Lemon
Values: (undef) red orange yellow
With Banana deleted
Keys: Apple Carrot Lemon
Values: red orange yellow ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.