我有這個代碼。此代碼運行良好,可以找到多個檔案之間的公共行。只是,我不知道如何將輸出從最高重復次數排序到最低次數。我希望將檔案排序為 6,6,5,5,4,3,2 而不是 5,3,2,6,4,5,6
輸出.txt
For line --> five
This line occurs 5 times in the following files: -
a.txt,
b.txt,
c.txt,
d.txt,
e.txt
For line --> three
This line occurs 3 times in the following files: -
a.txt,
b.txt,
c.txt
For line --> two
This line occurs 2 times in the following files: -
a.txt,
b.txt
For line --> eight
This line occurs 6 times in the following files: -
a.txt,
b.txt,
c.txt,
d.txt,
e.txt,
f.txt
For line --> four
This line occurs 4 times in the following files: -
a.txt,
b.txt,
c.txt,
d.txt
For line --> six
This line occurs 5 times in the following files: -
a.txt,
b.txt,
c.txt,
d.txt,
e.txt
For line --> seven
This line occurs 6 times in the following files: -
a.txt,
b.txt,
c.txt,
d.txt,
e.txt,
f.txt
The total common line between files are 7
腳本檔案 (perl)
#!/usr/bin/perl -w
my %hash;
my $file;
my $fh;
my $count;
for $file (@ARGV) {
open ($fh, $file) or die "$file: $!\n";
while(<$fh>) {
push @{$hash{ $_}}, $file;
}
}
for (keys %hash) {
$n = @{$hash{$_}};
if(@{$hash{$_}} > 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;
uj5u.com熱心網友回復:
您必須對鍵串列進行排序,而不是使用keys回傳的任意順序。perl 中一種有效的常用方法是使用Schwartzian Transform:
for (map { $_->[0] }
sort { $b->[1] <=> $a->[1] }
map { [ $_, scalar @{$hash{$_}} ] }
keys %hash) {
# ...
}
uj5u.com熱心網友回復:
您可以使用以下內容:
sort { @{ $hash{$b} } <=> @{ $hash{$a} } keys %hash
您還可以使用驚人的排序鍵分布。
use Sort::Key qw( rukeysort );
rukeysort { 0 @{ $hash{$_} } } keys %hash
建議使用 Schwartzian 變換。我認為這不是一個好的解決方案。
未經測驗,尚不清楚 Schwartzian 變換是否真的會提高性能,以及所有額外的呼叫塊和記憶體分配。它很可能使程式變得更復雜和更慢。
事實上,尚不清楚使用 ST 是否是一個好的解決方案。如果值得使用 ST,如果可以的話,最好使用 Sort::Key。它既簡單又快捷。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/504247.html
上一篇:Expect.pm:expect()給出“意外子程式”錯誤
下一篇:寫入一系列perl陣列
