用于读取文件内容的perl程序

时间:2014-10-05 14:04:03

标签: linux 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"
);

正如您可以清楚地看到的那样,我没有任何条款可以让用户输入要计算其出现次数的单词。因为我不知道该怎么做。请帮助计算发生部分的数量。谢谢

1 个答案:

答案 0 :(得分: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;
}
相关问题