Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Re: How do I empty out a hash?

by arno (Scribe)
on Oct 04, 2003 at 12:39 UTC ( #296498=note: print w/replies, xml ) Need Help??

in reply to How do I empty out a hash?


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.


Replies are listed 'Best First'.
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?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://296498]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2022-10-01 08:34 GMT
Find Nodes?
    Voting Booth?
    I prefer my indexes to start at:

    Results (126 votes). Check out past polls.