开发者

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

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 empt开发者_运维技巧y hashes?

If not, how can I make sure they point to empty hashes?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜