1

这就是我所拥有的

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

我的问题是为什么要创建这些附加键,它们本质上是先前创建的键-> 值对的值。

这是我所期望的

"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

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

4

3 回答 3

6

你的错误在你的 foreach 循环中,你需要这个keys函数:

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

否则,您foreach将遍历所有键和值。

于 2012-12-10T16:35:28.627 回答
5

问题是你没有使用

use strict;
use warnings;

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

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

或者类似的东西。

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

于 2012-12-10T16:38:51.463 回答
2

尝试:

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

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

于 2012-12-10T16:36:24.850 回答