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. What’s the difference between the two? Are they both identical ways to empty a hash?
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:
However, you should not use
undefto remove the value of anything except a scalar. For other variable types, set it to the “empty” version of that type — e.g. for arrays or hashes,@foo = (); %bar = ();