我想寫一個perl程序來打開一個文件並讀取它的內容並打印這些行,單詞和字符的數量。我也想打印文件中出現特定單詞的次數。這是我做了什麼:用於讀取文件內容的perl程序
#! /usr/bin/perl
open(FILE, "test1.txt") or die "could not open file $1";
my ($line, $word, $chars) = (0, 0, 0);
while (<FILE>) {
$line++;
$words += scalar(split(/\s+/, $_));
$chars += length($_);
print $_;
}
$chars -= $words;
print(
"Total number of lines in the file:= $line \nTotal number of words in the file:= $words \nTotal number of chars in the file:= $chars\n"
);
正如你可以清楚地看到,我沒有服用的,其發生量進行統計的話用戶輸入的任何規定。因爲我不知道該怎麼做。請幫助計數出現部位的數量。謝謝
如果你的文件沒有以換行符結束,你會錯過一個字符。 – Pierre 2014-10-05 19:36:35
爲什麼'$ chars - = $ words'? – 2014-10-05 19:47:29
@PeterR對於給定的行,字符數等於行的長度減去單詞的數量......考慮到每個單詞後跟一個間隔字符。但是,正如我在前面的評論中所指出的那樣,如果行不以換行符結尾(僅適用於最後一行),則不起作用。 – Pierre 2014-10-05 23:29:06