Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: How do I empty out a hash?

by DigitalKitty (Parson)
on Aug 16, 2003 at 01:51 UTC ( [id://284293]=note: print w/replies, xml ) Need Help??


in reply to How do I empty out a hash?

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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://284293]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (7)
As of 2024-04-18 02:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found