stdin使用perl检查文件中的字

igetnqfo  于 2022-11-15  发布在  Perl
关注(0)|答案(2)|浏览(145)

我有一个文件aa.txt:

Nothing is worth more than the truth.
I like to say hello to him.
Give me peach or give me liberty.
Please say hello to strangers.
I'ts ok to say Hello to strangers.

我试着用代码:

use strict;
use warnings;

my $input_aa='aa.txt';

while (1) {
    print "Enter the word you are looking for (or 'quit' to exit): ";
    my $answer = <STDIN>;
    chomp $answer;
    last if $answer =~/quit/i; #
    print "Looking for '$answer'\n";
    my $found = 0;
    open my $f, "<", $input_aa or die "ERROR: Cannot open '$input_aa': $!";
    while (<$f>) {
        m/$answer/ or next;
        $found=1;
        last;
    }
    close $f;
    if ($found) {
        print "Found $answer!\n";
        while ( my $line = <$input_aa> ) {
            print $line;
         }
    } else {
        print "Sorry - $answer was not found\n";
    }
}

我希望当我从键盘输入一个关键字时,在文件中进行比较,并输出带有该单词的行。例如,当我输入单词Nothing时,它应该输出行Nothing is worth more than the truth.
我试着输入代码,但是当我从钥匙串输入关键字时,它没有输出该行。问题在哪里?

4bbkushb

4bbkushb1#

您的代码可以正常工作,直到您尝试打印匹配行。您的代码尝试读取<$input_aa>,这不是一个有效的文件句柄。
相反,您可以使用$found变量在找到匹配行时简单地保存它,例如:

use strict;
use warnings;

my $input_aa='aa.txt';

while (1) {
    print "Enter the word you are looking for (or 'quit' to exit): ";
    my $answer = <STDIN>;
    chomp $answer;
    last if $answer =~/quit/i; #
    print "Looking for '$answer'\n";
    my $found;
    open my $f, "<", $input_aa or die "ERROR: Cannot open '$input_aa': $!";
    while (<$f>) {
        m/$answer/ or next;
        $found=$_;
        last;
    }
    close $f;
    if (defined($found)) {
        print "Found $answer! in this line: $found";
    } else {
        print "Sorry - $answer was not found\n";
    }
}

更改是不初始化$found,因此检查是否定义了$found。如果定义了,则打印$found

46scxncf

46scxncf2#

看来问题就出在这一行:

while ( my $line = <$input_aa> )

当你找到该行时,试着保存它,例如用以下内容替换$found = 1

$found = $_;

然后你可以打印$found

相关问题