| 
if (defined $hash{$key}) { } 
 
if (exists $hash{$key}) { } 
 
my %hash = (a => 1, b => 0, c => undef, e=>""); 
 
# key  value  defined  exists 
a          1        1       1 
b          0        1       1 
c      undef        0       1 
d      undef        0       0 
e      undef        1       1 
 
 
 
https://www.oreilly.com/library/view/perl-cookbook/1565922433/ch05s04.html 
 
You want to remove an entry from a hash so that it doesn¡¯t show up with `keys`, `values`, or `each`. If you were using a hash to associate salaries with employees, and an employee resigned, you¡¯d want to remove their entry from the hash. 
 
Use the `delete` function: 
 
``` 
# remove $KEY and its value from %HASH 
delete($HASH{$KEY}); 
``` 
 
Sometimes people mistakenly try to use `undef` to remove 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 a specific entry from a hash. Once you¡¯ve deleted a key, it no longer shows up in a `keys` list or an `each` iteration, and `exists` will return false for that key. 
 
This demonstrates the difference between `undef` and `delete`: 
 
``` 
# %food_color as per Introduction 
sub 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  now with the O¡¯Reilly learning platform. 
 
O¡¯Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.  | 
 |