需要像 open OR DIE 这样的东西,除了 chomp

Need something like open OR DIE except with chomp

我对编码还很陌生,我需要一个失败语句来打印出来,就好像它是 an or die 一样。

我的部分代码示例:

    print "Please enter the name of the file to search:";
    chomp (my $filename=<STDIN>) or die "No such file exists. Exiting program. Please try again."\n;

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

我需要它来完成这两个 print/chomp 语句。有什么要补充的吗?

整个节目:

#!/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:";
while (<>){
        print;
}

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

my $filename = <STDIN>;

my$ctr=0;
foreach( $filename ) {
        if ( /\b$input\b/ ) {
                $ctr++;
        }
}
print "Freq: $ctr\n";

exit;

您不需要测试文件句柄读取 <> 是否成功。参见 I/O Operators in perlop。当它没有什么可读的时候 returns 一个 undef,这正是你想要的,这样你的代码就知道什么时候停止阅读。

至于删除换行符,你还是要单独chomp。否则,一旦读取 return 一个 undef 你就会 chomp 一个未定义的变量,触发警告。

通常,在某些资源上打开文件句柄 $fh,您会这样做

while (my $line = <$fh>) {
    chomp $line;
    # process/store input as it comes ...
}

这也可以是 STDIN。如果肯定只是一行

my $filename = <STDIN>;
chomp $filename;

您也不需要测试 chomp 是否会失败。请注意,它 returns 是它删除的字符数,因此如果没有 $/ (通常是换行符)它合法地 returns 0.

补充一下,经常测试是一个很好的习惯!作为这种心态的一部分,请确保始终 use warnings;,我还强烈建议使用 use strict;.

进行编码

更新重要问题编辑

在第一个 while 循环中,您没有在任何地方存储文件名。鉴于打印的问候语,您应该只读取文件名而不是该循环。然后你阅读要搜索的词。

# print greeting

my $filename = <STDIN>;
chomp $filename;

my $input = <STDIN>;
chomp $input;

然而,我们遇到了更大的问题:您需要 open the file, and only then can you go through it line by line and search for the word. This is where you need the test. See the linked doc page and the tutorial perlopentut。首先检查是否存在同名文件。

if (not -e $filename) {
    print "No file $filename. Please try again.\n";
    exit;
}

open my $fh, '<', $filename  or die "Can't open $filename: $!";

my $word_count = 0;
while (my $line = <$fh>) 
{
    # Now search for the word on a line
    while ($line =~ /\b$input\b/g) {
        $word_count++;
    }
}
close $fh  or die "Can't close filehandle: $!";

上面的-e是文件测试之一,这个检查给定的文件是否存在。请参阅 file-tests (-X) 的文档页面。在上面的代码中,我们只是退出并显示一条消息,但您可能希望在循环中打印提示用户输入另一个名称的消息。

我们在正则表达式中使用 while/g 修饰符来查找该词在一行中的所有出现。

我还强烈建议您始终使用

启动您的程序
use warnings 'all';
use strict;