需要有'if'陈述的建议

时间:2016-11-17 01:00:58

标签: perl if-statement

我需要帮助调整我的代码块。一切正常,但随后它停止工作并且每次都失败(打印)。我做错了什么?

print "Enter a word to search for:";
chomp (my $word = <STDIN> );
if (not -e $word){
        print "No such word found.\n";
        exit;
}

整个计划。

#!/usr/bin/perl -w


use strict;


print "Welcome to the word frequency calculator.\n";
print "This program prompts the user for a file to open, \n";
print "then it prompts for a word to search for in that file,\n";
print "finally the frequency of the word is displayed.\n";
print " \n";


print "Please enter the name of the file to search:";
chomp (my $filename = <STDIN> );
if (not -e $filename){
        print "No such file exists. Exiting program. Please try again.
+\n";
        exit;
}


print "Enter a word to search for:";
chomp (my $word = <STDIN> );
if (not -e $word){
        print "No such word found.\n";
        exit;
}


print "Frequency of word: " . grep $word eq $_,
split /\W+/i, do { local (@ARGV, $/)= $filename; <> };


exit;

1 个答案:

答案 0 :(得分:5)

print "Welcome to the word frequency calculator.\n";
print "This program prompts the user for a file to open, \n";
print "then it prompts for a word to search for in that file,\n";
print "finally the frequency of the word is displayed.\n";
print " \n";

所以,根据这个,这个程序将......

  1. 要求用户提供要搜索的文件。
  2. 要求用户输入要搜索的字词。
  3. 检查该文字在该文件中的频率。
  4. 你有第一部分。

    print "Please enter the name of the file to search:";
    chomp (my $filename = <STDIN> );
    if (not -e $filename){
            print "No such file exists. Exiting program. Please try again.\n";
            exit;
    }
    

    虽然使用die代替print + exit可以更简洁地完成。而且通常不是检查文件是否存在,而应该尝试打开文件。文件可能存在但不可读。或者,当您选中时,它可能存在,然后在您稍后尝试打开时将其删除。

    print "Please enter the name of the file to search: ";
    chomp (my $filename = <STDIN> );
    open my $fh, "<", $filename or die "Sorry, couldn't open $filename because $!";
    

    然后对于第二位,您只需要提示单词。检查单词是否作为文件名存在是无稽之谈。

    print "Enter a word to search for: ";
    chomp (my $word = <STDIN> );
    

    最后,阅读文件并找到单词频率。您正在使用的代码很难理解......

    print "Frequency of word: " . grep $word eq $_,
      split /\W+/i, do { local (@ARGV, $/)= $filename; <> };
    

    ...它还会将整个文件丢入内存,如果文件变大,效率会很低。

    相反,使用while循环逐行读取文件。而不是将行拆分为单词,搜索/\Q$word\E/g行。 /g表示要从匹配的最后一个位置继续搜索。

    my $frequency = 0;
    while( my $line = <$fh> ) {
        while( $line =~ /\Q$word\E/g ) {
            $frequency++
        }
    }
    

    有关详细信息,请参阅perlretut