我需要帮助调整我的代码块.一切正常,但随后它停止工作并且每次都失败(打印).我究竟做错了什么?
print "Enter a word to search for:";
chomp (my $word = <STDIN> );
if (not -e $word){
print "No such word found.\n";
exit;
}
Run Code Online (Sandbox Code Playgroud)
整个计划.
#!/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;
Run Code Online (Sandbox Code Playgroud)
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";
Run Code Online (Sandbox Code Playgroud)
所以,根据这个,这个程序将......
你有第一部分.
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;
}
Run Code Online (Sandbox Code Playgroud)
虽然可以通过使用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 $!";
Run Code Online (Sandbox Code Playgroud)
然后对于第二位,您只需要提示单词.检查单词是否作为文件名存在是无稽之谈.
print "Enter a word to search for: ";
chomp (my $word = <STDIN> );
Run Code Online (Sandbox Code Playgroud)
最后,阅读文件并找到单词频率.您正在使用的代码很难理解......
print "Frequency of word: " . grep $word eq $_,
split /\W+/i, do { local (@ARGV, $/)= $filename; <> };
Run Code Online (Sandbox Code Playgroud)
...它还会将整个文件丢入内存,如果文件变大,效率会很低.
相反,使用while循环逐行读取文件.而不是将行分为单词,搜索行/\Q$word\E/g./g说从你匹配的最后一个地方继续搜索.
my $frequency = 0;
while( my $line = <$fh> ) {
while( $line =~ /\Q$word\E/g ) {
$frequency++
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅perlretut.