我上周剛開始學習 Perl。
我必須在這個目錄中有兩個檔案。但稍后我可能想在同一目錄中添加 100 個 txt 檔案。這種編碼的目的是統計每個單詞出現的頻率。
File1:
e
f
g
h
a
File2:
a
b
c
d
e
為了方便計數,我需要將所有文本檔案讀入同一個陣列。
所以這是我的腳本。
my $dir = 'C:\Perl_Example\Data\New';
my %count;
my $line;
foreach my $fp (glob("$dir/*.txt"))
{
open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
#open file to read which is each file in dir
while (my $line = <$fh>) #line by line to array
{
chomp $line;
foreach my $str ($line =~ /\w /g)
{
$count{$str} ;
printf "%-31s %s\n", $str, $count{$str};
}
}
}
我預計結果會是這樣
f 1
g 1
h 1
a 2
b 1
c 1
d 1
e 2
但它變成了這樣
e 1
f 1
g 1
h 1
a 1
a 2
b 1
c 1
d 1
e 2
請指教。
uj5u.com熱心網友回復:
在處理完所有檔案之前不要列印任何內容。
foreach my $fp (glob("$dir/*.txt"))
{
open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR";
#open file to read which is each file in dir
while (my $line = <$fh>) #line by line to array
{
chomp $line;
foreach my $str ($line =~ /\w /g)
{
$count{$str} ;
}
}
}
# We have now processed all of the files and have all of
# our data in %count.
for (keys %count) {
printf "%-31s %s\n", $_, $count{$_};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371915.html
