2014-10-05 28 views
1

我想寫一個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" 
); 

正如你可以清楚地看到,我沒有服用的,其發生量進行統計的話用戶輸入的任何規定。因爲我不知道該怎麼做。請幫助計數出現部位的數量。謝謝

+0

如果你的文件沒有以換行符結束,你會錯過一個字符。 – Pierre 2014-10-05 19:36:35

+0

爲什麼'$ chars - = $ words'? – 2014-10-05 19:47:29

+0

@PeterR對於給定的行,字符數等於行的長度減去單詞的數量......考慮到每個單詞後跟一個間隔字符。但是,正如我在前面的評論中所指出的那樣,如果行不以換行符結尾(僅適用於最後一行),則不起作用。 – Pierre 2014-10-05 23:29:06

回答

0

我想你是爲了學習的目的這樣做,所以這裏有一個很好的可讀版本的問題(可能有一千個,因爲它是perl)。如果不是,則在linxux命令行上有wc

請注意,我使用三個參數打開,這通常會更好。 對於計算單個單詞,你很可能需要一個散列。我使用<<HERE文檔,因爲它們更適合格式化。如果您有任何疑問,只需查看perldoc並提出問題。

#!/usr/bin/env perl 

use warnings; # Always use this 
use strict;  # ditto 

my ($chars,$word_count ,%words); 
{ 
    open my $file, '<', 'test.txt' 
    or die "couldn't open `test.txt':\n$!"; 
    while (<$file>){ 
    foreach (split){ 
     $word_count++; 
     $words{$_}++; 
     $chars += length; 
    } 
} 
} # $file is now closed 

print <<THAT; 
Total number of lines: $. 
Total number of words: $word_count 
Total number of chars: $chars 
THAT 

# Now to your questioning part: 
my $prompt= <<PROMPT.'>>'; 
Please enter the words you want the occurrences for. (CTRL+D ends the program) 
PROMPT 
print $prompt; 

while(<STDIN>){ 
    chomp; # get rid of the newline 
    print "$_ ".(exists $words{$_}?"occurs $words{$_} times":"doesn't occur") 
    ." in the file\n",$prompt; 
} 
+1

'我做了一個程序,其中我使用了$ wordcountinline = scalar(split(/ $ searchword /,$ _)。這個工作正常,但它也適用於字符。也就是說,如果我輸入'j',然後發現字符'j'發生了多少次,但是你的程序運行正常,謝謝 – Pranjal 2014-10-09 17:39:34

+0

@Pranjal:你不需要在你的行中顯式的'scalar',你真的應該使用'嚴格「和」警告「 – 2014-10-09 18:51:03

+0

什麼是」嚴格「和」警告「用於? – Pranjal 2014-10-10 05:04:22