You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Perl中按重复频率从高到低排序多文件公共行输出

如何让Perl脚本按重复次数从高到低输出多文件公共行?

你需要修改遍历哈希的部分,让它按每行的出现次数降序排序后再输出。Perl里哈希的默认遍历顺序是随机的,所以得用sort函数指定排序规则。

修改后的完整脚本如下:

#!/usr/bin/perl -w
my %hash; 
my $file;
my $fh;
my $count;

for $file (@ARGV) {
    open ($fh, $file) or die "$file: $!";
    while(<$fh>) {
        push @{$hash{ $_}}, $file;
    } 
}
# 按出现次数从高到低排序哈希键
for (sort { @{$hash{$b}} <=> @{$hash{$a}} } keys %hash) {
    my $n = @{$hash{$_}};
    if($n > 1) {
        $count ++;
        print "\n For line --> $_\n";
        print "This line occurs $n times in the following files: - \n", join(",\n", @{$hash{$_}}), "\n\n";
    }
}
print "The total common line between files are $count\n";  
exit 0;

修改说明:

把原来的for (keys %hash)替换成sort { @{$hash{$b}} <=> @{$hash{$a}} } keys %hash:

  • @{$hash{$b}} <=> @{$hash{$a}}是Perl的数值比较运算符,$b在前表示降序排列(如果要升序就换成$a在前)
  • 这个排序规则会根据每行对应的文件列表长度(也就是出现次数)来排序,次数多的行先输出

这样修改后,输出就会按照你期望的顺序:6,6,5,5,4,3,2来展示结果了。

内容的提问来源于stack exchange,提问作者abcd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:54:21