Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a Perl hash

Tags:

perl

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?

like image 439
Haiyuan Zhang Avatar asked Aug 01 '10 04:08

Haiyuan Zhang


People also ask

How do I undef a hash in Perl?

undef on hash elements The script uses $h{Foo} = undef; to set the value of a hash key to be undef. use strict; use warnings; use Data::Dumper qw(Dumper);

How do I delete a scalar in Perl?

Perl | delete() Function Delete() in Perl is used to delete the specified keys and their associated values from a hash, or the specified elements in the case of an array.


1 Answers

%$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.

like image 121
Axeman Avatar answered Sep 26 '22 06:09

Axeman