我有令人费解的行为,其中 perl 凭空制造一个“空”散列键。我只是从现有的哈希中获取密钥并使用相同的密钥创建一个新的哈希。尽管原始哈希中只有 15 个密钥,但新形成的哈希获得了神秘的第 16 个密钥。
相关代码如下:
DO_SOMETHING(\%Hash1, \%Hash2);
sub DO_SOMETHING {
my %Hash3 = undef;
my $count = 0; # reset counter
my ($Hash1Ref, $Hash2Ref) = @_; # grab arguments to subroutine
my %Hash1 = %$Hash1Ref; # dereference hash #1
my %Hash2 = %$Hash2Ref; # dereference hash #1
my @Hash2keys = sort {$a <=> $b} keys %Hash2; # grab keys from Hash #2
print "Hash #2 keys = ", join (',', @Hash2keys), "\n"; # print keys in Hash # 2
my $NumHash2keys = @Hash2keys;
print "Number of Hash #2 keys = $NumHash2keys\n"; # print number of keys in Hash #2
print "Building new hash (Hash #3) using keys from Hash #2\n";
foreach my $Hash2key (@Hash2keys) { # iterate through Hash # 2 keys
$count ++; # count number of iterations
$Hash3{$Hash2key} = 1 # mirror keys from Hash #2 in a new hash (Hash #3)
}
print "Number of Hash #2 key iterations = $count\n"; # confirm number of iterations through Hash #2 keys
my @Hash3keys = keys %Hash3;
print "Hash #3 keys = ", join (',', @Hash3keys), "\n";
my $NumHash3keys = @Hash3keys;
print "Number of Hash #3 keys = $NumHash3keys\n";
}
这是输出:
哈希 #2 键 = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
哈希 #2 键的数量 = 15
使用哈希 #2 中的密钥构建新哈希(哈希 #3)
哈希#2密钥迭代次数 = 15
哈希 #3 键 = 1,10,4,12,3,13,6,2,15,14,7,,11,9,8,5
哈希 #3 键的数量 = 16
我一辈子都无法弄清楚第 16 个“null”键是从哪里来的。它似乎是在隐形循环期间分配的。
请勿使用
%Hash3
初始化 undef
。
改变:
my %Hash3 = undef;
至:
my %Hash3;
您的问题是%Hash3的初始化。
您无需设置任何内容。
undef 对于引用有意义,而不是对于哈希或数组