Structure
Structure

Reputation: 842

How can I reset a hash completely without using a for loop?

I would like to completely reset my %hash so that it does not contain keys or values at all. I prefer to use a one-liner than have to use a loop.

So far I have tried:

%hash = 0;
%hash = undef;

But these both throw errors in strict mode with warnings enabled, so I wrote a simple for loop to achieve the same thing:

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

This works but I would really like to do this with a one-liner. Is there a way to simply reset a hash that I am overlooking?

Upvotes: 17

Views: 18214

Answers (7)

kkoolpatz
kkoolpatz

Reputation: 156

Since the OP asked for a one liner that works with use strict and warnings

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

Upvotes: 0

Pramodh
Pramodh

Reputation: 199

%hash = (); must work

Upvotes: 1

rafl
rafl

Reputation: 12341

Both %hash = (); and undef %hash; will work, with the difference that the latter will give back some memory to use for other things. The former will keep the memory the things in the hash used before, assuming it'll be used again later anyway, when the hash is being refilled.

You can use Devel::Peek to observe that behaviour:

$ perl -MDevel::Peek -we'my %foo = (0 .. 99); %foo = (); Dump \%foo; undef %foo; Dump \%foo'
SV = IV(0x23b18e8) at 0x23b18f0
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x23acd28
  SV = PVHV(0x23890b0) at 0x23acd28
    REFCNT = 2
    FLAGS = (PADMY,SHAREKEYS)
    ARRAY = 0x23b5d38
    KEYS = 0
    FILL = 0
    MAX = 63
    RITER = -1
    EITER = 0x0
SV = IV(0x23b18e8) at 0x23b18f0
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x23acd28
  SV = PVHV(0x23890b0) at 0x23acd28
    REFCNT = 2
    FLAGS = (PADMY,SHAREKEYS)
    ARRAY = 0x0
    KEYS = 0
    FILL = 0
    MAX = 7
    RITER = -1
    EITER = 0x0

The MAX fields in the PVHVs are the important bit.

Upvotes: 38

Thilo
Thilo

Reputation: 262832

How about

%hash = ();

Upvotes: 7

Thariama
Thariama

Reputation: 50840

Use

%hash = ();

Upvotes: 2

Eugene Yarmash
Eugene Yarmash

Reputation: 150138

You can use undef:

undef %hash;

Upvotes: 5

codaddict
codaddict

Reputation: 455430

You can do:

%hash = ();

Upvotes: 2

Related Questions