Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Answer: How do I empty out a hash?

( #296498=categorized answer: print w/ replies, xml ) Need Help??

Q&A > hashes > How do I empty out a hash? contributed by arno

Hi,

To delete a key, you don't need to know her value.
Here's my code :

my %hash = ( Carol => 22, Mary => 21, Chris => 30 ); map { delete $hash{$_} } keys %hash;
Update: Of course this makes use of map in void context. Yick. And a couple other suggestions came in by way of followup:

  • delete @hash{(keys %hash)}; # Hash slice
  • %hash = (); # Most efficient method.

Arnaud

Comment on Answer: How do I empty out a hash?
Select or Download Code
Re: Answer: How do I empty out a hash?
by Aristotle (Chancellor) on Oct 04, 2003 at 16:10 UTC
    Easier yet.
    delete @hash{(keys %hash)};
    Update: this is, of course, only useful when you want to use delete the keys from one hash in another one, as in
    delete @foo{(keys %bar)};
    Otherwise, only the below solution makes any sense.

    Makeshifts last the longest.

      Even more easier!

      %hash = ();

      And twice more quicker also.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2015-07-06 20:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (82 votes), past polls