-1

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

我的部分代码示例:

    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;
4

1 回答 1

2

您不需要测试文件句柄读取<>是否成功。请参阅perlop 中的 I/O 运算符。当它没有要读取的内容时,它会返回一个undef,这正是您想要的,因此您的代码知道何时停止阅读。

至于删除换行符,无论如何你都想单独咀嚼否则,一旦读取确实返回了一个未定义的变量,undef就会chomp触发警告。

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

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

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

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

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

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


更新一个重要的问题编辑

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

# print greeting

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

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

但是,接下来我们会遇到更大的问题:您需要打开文件,然后才能逐行浏览并搜索单词。这是你需要测试的地方。请参阅链接的文档页面和教程perlopenut。首先检查是否存在具有该名称的文件。

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

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

我还强烈建议您始终以

use warnings 'all';
use strict;
于 2016-11-16T23:39:56.270 回答