- Perl ›
- builtin functions ›
- here

## delete function - delete hash key

You can use the ** delete function ** to delete hash key. The value corresponding to the key is also deleted. The return value is the value that corresponds to the deleted key.

my $value = delete $hash{$key};

To use the delete function for hash reference, write:

my $value = delete $hash->{$key};

This is an example to delete the key named age using the delete function.

# Removed the key age my %person = (name =>'Ken', age => 19); delete $person{age};

This is an example for a hash reference.

# Delete the key. For reference. my $person = {name =>'Ken', age => 19}; delete $person->{age};

### Example program

You can see the output with an example that removes the hash key.

use strict; use warnings; use Data::Dumper; # Student math scores my %math_scores = ( Aiko => 89, Kenta => 0, Taro => undef ); # 1: Initial state print "1: Initial state\n"; if (exists $math_scores{Aiko}) { print "\$math_scores{Aiko} exists.\n"; } print Data::Dumper->Dump([\%math_scores], ['*math_scores']); print "\n\n"; # Delete the key with delete delete $math_scores{Aiko}; # 2: Deleted by delete print "2: Deleted by delete\n"; if (exists $math_scores{Aiko}) { print "\$math_scores{Aiko} exists.\n"; } else { print "\$math_scores{Aiko} does not exist.\n"; } print Dumper \%math_scores; print "\n";

Output

1: Initial state $math_scores{Aiko} exists. %math_scores = ( 'Aiko' => 89, 'Kenta' => 0, 'Taro' => undef ); 2: Deleted by delete $math_scores{Aiko} does not exist. %math_scores = ( 'Kenta' => 0, 'Taro' => undef );