【问题标题】:return entire line when search string is found找到搜索字符串时返回整行
【发布时间】:2026-01-07 02:40:02
【问题描述】:

当我在该行中找到搜索字符串时,我想返回整行。

当我打印时,我得到了我需要的大部分内容,但我的字符数少了大约 10 个。我得到了行的开头和字符串以及之后大约 10 个字符,但仅此而已。

这是我的代码(提前致谢):

use strict;
use warnings;

my $calls_dir = "Ask/";
opendir(my $search_dir, $calls_dir) or die "$!\n";
my @files = grep /\.txt$/i, readdir $search_dir;
closedir $search_dir;
print "Got ", scalar @files, " files\n";

#my %seen = ();
foreach my $file (@files) {
    my %seen = ();
    my $current_file = $calls_dir . $file;
    open my $FILE, '<', $current_file or die "$file: $!\n";


    while (<$FILE>) {
        chomp;
        if (/^*(.*)Contact\s*(.*)\r?$/i) {
            $seen{$1} = 1;

            foreach my $addr ( sort keys %seen ) {

                print "\n";
                print $file;
                print "\n";
                print "[$addr]\n";
                print "\n";
                print "\n";
            }
        }
    }
    close $FILE;
}

【问题讨论】:

  • 发布一些输入和一些输出
  • 如果您将 /^*(.*)Contact\s*(.*)\r?$/i 称为您要匹配的模式,$_ 将包含整行 - 即在 if 语句之后执行 print "$_\n";
  • 那之后的下一行怎么样?那之后的呢?我知道我很蹩脚,但我对 perl 很陌生,所以我真的很感激。

标签: regex string perl printing line


【解决方案1】:

$_ 包含您要查找的整行

【讨论】: