我如何在Perl中创建一个新的空哈希引用? [英] How can I make a new, empty hash reference in Perl?
问题描述
#%superhash是一些具有多于0个键的预定义散列;
%hash =();
foreach我的$ key(键值%superhash){
$ superhash {$ key} =%hash;
%hash =();
$ / code>
superhash的所有键都指向与%hash
或者它们会是不同的空哈希?
如果不是,我怎么确定它们指向空哈希? 复制到复数数据类型(数组或散列),然后才能将其存储到其中一个单独的插槽中。但是在给出的示例代码中,如果引用它们,每个代码都是相同的散列。
初始化数据结构的方式是:
foreach my $ key(keys%superhash){
$ superhash {$ key} = {}; #新的空散列引用
}
但是,像这样的初始化在 Perl 由于autovivification(当变量用作容器时创建适当的容器对象)。
my%hash;
$ hash {a} {b} = 1;
现在%hash
有一个键,'' a',其具有匿名hashref的值,其包含键/值对 b => 1
。数组以相同的方式自动生成。
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?
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.
这篇关于我如何在Perl中创建一个新的空哈希引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!