我找到了讀取目錄中所有文本檔案的代碼。但我不知道如何找到它們之間的共同點。請幫助我撰寫代碼,或分享我需要探索更多的領域。要學的東西太多,但我有時間限制。
use strict;
use warnings;
use English;
my $dir = 'C:\Perl_Example\Data';
foreach my $fp (glob("$dir/*.txt"))
{
printf "%s\n", $fp;
#the file header
open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
#open file to read which is each file in dir
while (<$fh>)
{
printf " %s", $_;
#print the file content
}
close $fh or die "can't read close '$fp': $OS_ERROR";
}
uj5u.com熱心網友回復:
這是“找到共同點”的一種方法。當然,在 Perl 中有不止一種方法可以做到這一點 :)
#!/usr/bin/perl -w
my %h;
for my $file (@ARGV) {
open (my $fh, $file) or die "$file: $!\n";
while(<$fh>) {
chomp;
push @{$h{$_}}, $file;
}
}
for (sort keys %h) {
if(@{$h{$_}} > 1) {
print "line <$_>\n";
print " occurs in ", join(", ", @{$h{$_}}), "\n";
}
}
exit 0;
現在是名為 {1,2,3} 的測驗檔案:
% cat 1
PING YA.RU (87.250.250.242): 56 data bytes
64 bytes from 87.250.250.242: icmp_seq=0 ttl=249 time=14.615 ms
64 bytes from 87.250.250.242: icmp_seq=1 ttl=249 time=14.943 ms
64 bytes from 87.250.250.242: icmp_seq=2 ttl=249 time=14.381 ms
64 bytes from 87.250.250.242: icmp_seq=3 ttl=249 time=14.852 ms
64 bytes from 87.250.250.242: icmp_seq=4 ttl=249 time=14.791 ms
% cat 2
PING YA.RU (87.250.250.242): 56 data bytes
64 bytes from 87.250.250.242: icmp_seq=0 ttl=249 time=14.615 ms
64 bytes from 87.250.250.242: icmp_seq=3 ttl=249 time=14.852 ms
64 bytes from 87.250.250.242: icmp_seq=4 ttl=249 time=14.791 ms
% cat 3
64 bytes from 87.250.250.242: icmp_seq=3 ttl=249 time=14.852 ms
64 bytes from 87.250.250.242: icmp_seq=4 ttl=249 time=14.791 ms
并測驗腳本運行:
% ./try.pl 1 2 3
line <64 bytes from 87.250.250.242: icmp_seq=0 ttl=249 time=14.615 ms>
occurs in 1, 2
line <64 bytes from 87.250.250.242: icmp_seq=3 ttl=249 time=14.852 ms>
occurs in 1, 2, 3
line <64 bytes from 87.250.250.242: icmp_seq=4 ttl=249 time=14.791 ms>
occurs in 1, 2, 3
line <PING YA.RU (87.250.250.242): 56 data bytes>
occurs in 1, 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417093.html
標籤:
上一篇:RabitMQ 簡介
