tags:

views:

68

answers:

2

Let's say we define an anonymous hash like this:

my $hash = {};

And then use the hash afterwards. Then it's time to empty or clear the hash for reuse. After some Google searching, I found:

%{$hash} = () 

and:

undef %{$hash}

Both will serve my needs. My question is, what's the difference between the two? Are they both identical ways to empty a hash?

+6  A: 

%$hash_ref = (); makes more sense than undef-ing the hash. Undef-ing the hash says that you're done with the hash. Assigning an empty list says you just want an empty hash.

Axeman
+7  A: 

Yes, they are absolutely identical. Both remove any existing keys and values from the table and sets the hash to the empty list.

See perldoc -f undef:

undef EXPR
undef   Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using "@"), a hash (using "%"), a subroutine (using "&"), or a typeglob (using "*")...
Examples:

               undef $foo;  
               undef $bar{'blurfl'};      # Compare to: delete $bar{'blurfl'};  
               undef @ary;  
               undef %hash;
Ether