2016-11-16 47 views
-1

我是相当新的编码,我需要一个失败声明打印出来,就好像它是一个或死亡。作为例子来我的代码需要类似开放或死亡,除了与chomp

部分:

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

我需要做的是为这两个打印/格格语句。无论如何只要加上这个?

整个程序:

#!/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; 
+2

开始你的计划我有点在你的程序中的逻辑困惑,错误消息表明您正在做的事情有一个文件,但在这点它所做的就是从标准输入读取 – adrianp

+0

我可以发布整个程序,但我不明白它会如何帮助,虽然考虑我的问题。 – distro

+0

哦,这个更新改变了一点,不是吗。我的答案代表了从'<>'和'chomp'测试读取的原始问题。我会更新到这个新内容。 – zdim

回答

2

你并不需要测试的文件句柄读<>成功。见I/O Operators in perlop。当它没有什么可读的时候,它会返回一个undef,这正是你想要的,所以你的代码知道什么时候停止阅读。

至于删除换行符,你想分开chomp。否则,一旦读取确实返回undef,那么您将在未定义的变量上触发警告。

通常情况下,一个文件句柄$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; 

然而,然后我们得到了更大的问题:你需要open文件,也只有这样,你可以通过它去一行一行地搜索单词。这是你需要测试的地方。请参阅链接的文档页面和教程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修饰符来查找一行中单词的所有出现。

我想也强烈建议总是与

​​
+0

但我想,我知道我不需要。 – distro

+0

@distro好的,原则上非常好 - 但是用'chomp'你不会想__。它返回一些删除的字符,所以如果它没有找到新行,它会返回一个零。因此,“正常”测试(使用'或')会导致错误的原因。如果你担心一个内​​建函数调用只是_failing_,那么你将不得不几乎测试每一个语句! – zdim

+0

好的,我很欣赏这个建议。但是有没有办法做到这一点?如果用户放入的文件不存在,我希望我的程序退出并显示自己的消息。 – distro