删除哈希中键的重复值

use*_*029 2 perl hash

我有以下代码

chdir("c:/perl/normalized");
$docid=0;
my %hash = ();
@files = <*>;
foreach $file (@files) 
  {
    $docid++;
    open (input, $file);    
    while (<input>) 
      {
    open (output,'>>c:/perl/tokens/total');
    chomp;
    (@words) = split(" ");  
    foreach $word (@words)
    {
    push @{ $hash{$word} }, $docid;

    }
      }
   }
foreach $key (sort keys %hash) {
    print output"$key : @{ $hash{$key} }\n";
}


close (input);
close (output);
Run Code Online (Sandbox Code Playgroud)

这是文件中的示例输出

of : 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 4 4 4 4 5 6 6 7 7 7 7 7 7 7 7 7
Run Code Online (Sandbox Code Playgroud)

这是真的,因为例如“of”一词在第一个文档中出现了 10(十次),但是有没有办法删除重复的值;即我想要一个而不是十个 谢谢你的帮助

ike*_*ami 5

为了避免首先添加重复项,请更改

foreach $word (@words)
Run Code Online (Sandbox Code Playgroud)

foreach $word (uniq @words)
Run Code Online (Sandbox Code Playgroud)

如果您想在数据结构中保留重复项,请改为更改

print output"$key : @{ $hash{$key} }\n";
Run Code Online (Sandbox Code Playgroud)

print output "$key : ", join(" ", uniq @{ $hash{$key} }), "\n";
Run Code Online (Sandbox Code Playgroud)

uniq 由 List::MoreUtils 提供。

use List::MoreUtils qw( uniq );
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

sub uniq { my %seen; grep !$seen{$_}++, @_ }
Run Code Online (Sandbox Code Playgroud)