出來沒有在那裏,我在我的代碼神祕鑰匙在Perl 5.14哈希表
my %stat =();
# read files and do some initialization
# like $stat{$key} = {k1=>v1, k2=>v2, k3=>v3};
# I have located the buggy code
# I want to do something according to c1 and c2 parsed from each line of the file
if(!exists $stat{c1}) { # I thought I would have initialized all possible used keys here, but it is not true as seen below
$stat{c1} = {k1=>0, k2=>0, k3=>0};
}
if($c1 == $c2) {
$stat{c1}{k1}++;
} else {
$stat{c1}{k2}++;
$stat{c2}{k3}++; #Note: I forgot to check whether $stat{c2} has been initialized here!
}
map {
my $val = $stat{$_}{k1};
print "$val\n"; # run time error shows "use of uninitalized $val"
} keys %stat;
使用哈希表我寫了一些打印語句來調試程序。我發現一些關鍵值神奇地出現在哈希表「%stat」中,儘管我從未插入它!說$ stat {510}儘管我永遠不會插入它,但它的值(在我的情況下是一個哈希表引用)沒有初始化。我必須寫一份聲明:
map { delete $stat{$_} if(!defined $stat{$_}{k1}) } keys %stat;
刪除不需要的密鑰。
你能告訴我爲什麼一些神祕的鑰匙可以出現(鍵%stat)?
感謝, 傑夫
它被稱爲 「自動激活」。 – varnie
'if(c1 == c2)'?這看起來非常錯誤。錯字,應該是'$ c1'和'$ c2'? – TLP
是的。感謝您的更正。 – Fashandge