You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl脚本实现STDIN输入关键词查找文件行问题排查

Perl文件查找无法输出匹配行的问题分析及修复

场景与问题

我有一个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.

尝试使用以下Perl代码实现:从键盘输入关键词,在文件中查找并输出包含该关键词的行(例如输入Nothing时,输出对应行),但运行后无法输出对应行:

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";
    }
}

问题根源

  1. 文件句柄误用:代码关闭文件句柄$f后,尝试用文件名$input_aa作为文件句柄读取内容(while ( my $line = <$input_aa> )),这是完全错误的——<$input_aa>会将字符串当作文件句柄,无法读取目标文件内容。
  2. 逻辑冗余且错误:第一次打开文件时,找到匹配行就立刻last退出循环,仅标记found=1就关闭文件,之后没有重新读取文件来输出匹配行的逻辑,自然无法打印内容。

修复后的代码

直接在一次文件读取过程中完成查找与输出,简化逻辑:

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 (my $line = <$f>) {
        # 若需要忽略大小写匹配,可改为 if ($line =~ /$answer/i)
        if ($line =~ /$answer/) {
            print $line;
            $found = 1;
        }
    }
    close $f;
    
    if (!$found) {
        print "Sorry - $answer was not found\n";
    }
}

关键修改点

  • 移除冗余的“先判断是否存在,再重新读取”逻辑,直接在遍历文件时输出匹配行;
  • 保留$found变量用于判断是否有匹配项,无匹配时提示用户;
  • 若需要忽略大小写匹配,将正则改为/$answer/i即可适配hello和Hello的匹配需求。

内容的提问来源于stack exchange,提问作者Trí Trương

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:40:39