由autovivification创建的哈希有额外的密钥

时间:2012-12-10 16:33:22

标签: perl hash autovivification

这就是我所拥有的

my %count_words;

while (<DATA>){
    my $line= $_;
    chomp $line;
    my @words = split (/ /, "$line");
    foreach my $word(@words){
        $count_words{"$word"}++;
    }
}

foreach my $key (%count_words){
    print "\"$key\" occurs \"$count_words{$key}\" times\n";
}

__DATA__
we name is something
this is what it does
we food food food food

这是我得到的输出

"it" occurs "1" times
"1" occurs "" times
"what" occurs "1" times
"1" occurs "" times
"name" occurs "1" times
"1" occurs "" times
"food" occurs "1" times
"1" occurs "" times
"does" occurs "1" times
"1" occurs "" times
"is" occurs "2" times
"2" occurs "" times
"we" occurs "2" times
"2" occurs "" times
"food" occurs "3" times
"3" occurs "" times
"something" occurs "1" times
"1" occurs "" times
"this" occurs "1" times
"1" occurs "" times

我的问题是为什么创建的这些附加键基本上是先前创建的key-&gt;值对的值。

这就是我所期待的

"it" occurs "1" times
"what" occurs "1" times
"name" occurs "1" times
"food" occurs "1" times
"does" occurs "1" times
"is" occurs "2" times
"we" occurs "2" times
"food" occurs "3" times
"something" occurs "1" times
"this" occurs "1" times

有人可以纠正我明显的错误吗?

3 个答案:

答案 0 :(得分:6)

您的错误发生在您的foreach循环中,您需要keys函数:

foreach my $key ( keys %count_words){
    print "\"$key\" occurs \"$count_words{$key}\" times\n";
}

否则,您的foreach正在遍历所有键和值。

答案 1 :(得分:5)

问题是你没有使用

use strict;
use warnings;

如果你有,它会给你一个关于你的代码中的错误的线索

Use of uninitialized value $count_words{"1"}...

或者那种效果。

问题是,正如Tim A已经指出的那样,您正在使用列表上下文中的哈希,这意味着它会扩展为键和值。您应该像他建议的那样使用keys函数。

答案 2 :(得分:2)

尝试:

foreach my $key (keys %count_words){
    print "\"$key\" occurs \"$count_words{$key}\" times\n";
}

问题在于,当您遍历哈希时,您会交替遍历键值。