Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

How to clear a Perl hash

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?

question from:https://stackoverflow.com/questions/3380780/how-to-clear-a-perl-hash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

However, you should not use undef to 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 = ();


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...