How can I make a new, empty hash reference in Perl?

hash, perl, reference

Solution

You need to use the `\` operator to take a reference to a plural data type (array or hash) before you can store it into a single slot of either. But in the example code given, if referenced, each would be the same hash.

The way to initialize your data structure is:

foreach my $key (keys %superhash) {
    $superhash{ $key } = {}; # New empty hash reference
}

But initialization like this is largely unnecessary in Perl due to autovivification (creating appropriate container objects when a variable is used as a container).

my %hash;

$hash{a}{b} = 1;

Now `%hash` has one key, 'a', which has a value of an anonymous hashref, containing the key/value pair `b => 1`. Arrays autovivify in the same manner.

Problem

Say I had something like: ``` # %superhash is some predefined hash with more than 0 keys; %hash = (); foreach my $key (keys %superhash){ $superhash{ $key } = %hash; %hash = (); } ``` Would all the keys of superhash point to the same empty hash accessed by `%hash` or would they be different empty hashes? If not, how can I make sure they point to empty hashes?

Original source