Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Answer: How do I empty out a hash?

by DigitalKitty (Parson)
on Aug 16, 2003 at 01:51 UTC ( #284293=categorized answer: print w/replies, xml ) Need Help??

Q&A > hashes > How do I empty out a hash? - Answer contributed by DigitalKitty

Hi.

You could also iterate over the hash and delete each key/value pair with this:
#!/usr/bin/perl -w use strict; my %hash = ( Carol => 22, Mary => 21, Chris => 30 ); my( $k, $v); while(( $k, $v) = each %hash ) { delete $hash{$k}; }

The previous solutions are more efficient but I thought you might appreciate an alternate method.

Update: Several followups included these suggestions:

  • for (keys %hash) { delete $hash{$_};};
  • delete $hash{$_} for keys %hash;

Both of those methods ignore the values, which are unimportant when deleting hash table entries.



Hope this helps,
-Katie

Replies are listed 'Best First'.
Re: Answer: How do I empty out a hash?
by liz (Monsignor) on Aug 16, 2003 at 15:58 UTC
    The quick way to clear a hash is
    %hash = ();
    i.e. set the empty list as the hash. Even if the hash is tied, a properly implemented tieing module should implement both the DELETE and CLEAR functions, so it should work in that case as well.

    Liz

Re: Answer: How do I empty out a hash?
by NetWallah (Canon) on Aug 16, 2003 at 04:52 UTC
    If you really wanted to iterate over the hash, using katie's method, there is no point in fetching the VALUE, only to throw it away. Hence, I'd code it thus:
    #!/usr/bin/perl -w use strict; my %hash = ( Carol => 22, Mary => 21, Chris => 30 ); for (keys %hash){ delete $hash{$_}; };
    which is a little easier on the eye ...
      That builds a list of keys up front - may or may not be a bad idea. If it is, I use each in scalar context to get something similar looking:
      my $k; delete $hash{$k} while $k = each %hash;
      (Incidentally, I'd write your version like so:)
      delete $hash{$_} for keys %hash;

      Makeshifts last the longest.

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: (3)
As of 2020-04-05 21:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The most amusing oxymoron is:
















    Results (35 votes). Check out past polls.

    Notices?