Perl: remove key from a hash

How to remove any key from a given hash? There is a function delete() at Perl. Using the function, you can easily delete any element from the Perl hash. Here is an example

## initial Hash with few elements
my %hash = (apple => 10, pine => 20, ball => 19, code => 99);
## printing your hash
while(my($key, $value) = each(%hash)){
print "$key => $value\n";
}
print "\n";

## removing one key from the hash
delete($hash{ball});
## printing again, to see the change
while(my($key, $value) = each(%hash)){
print "$key => $value\n";
}


Output:

pine => 20
apple => 10
ball => 19
code => 99

pine => 20
apple => 10
code => 99


At the above function, I have first declared a hash with few elements. Then printed all the elements from the hash into the screen. After that I have just deleted one element from the hash, and printed the elements from hash into screen once again. You'll find that the 'ball' element from the hash is removed by the delete() function of Perl.

You can use undef() from Perl to unset the hash. But it will not remove the key from the hash. That's why using the delete() function comes up. But still you can use undef for unset the Perl hash. Here is the example how you can do that.
undef($hash{ball});  ## undef using key name
$hash{code} = undef; ## undef the value directly


You can see the effect by printing the hash after using undef, and you'll find that the key is exist, but the values are gone. The above two undef will remove the two elements from the initial hash. And the output will look like as below.
pine => 20
apple => 10
ball =>
code =>


Thanks guys for reading the post.
Wolf
(icfun.blogspot.com)

Comments

Unknown said…
Just wanted to say Thanks. This was indeed helpful