1

我想在 perl 中读取一个文件,之后,用户可以输入任何字符串,grep 会尝试在读取的文件中找到输入的字符串。它只会在用户不输入任何内容或任何空格字符时退出。这是我的代码不起作用:

#! usr/bin/perl
use warnings;
use strict;

open MATCHSTRING,"matchstring";
my @lines = <MATCHSTRING>;

while (<>) {
    chomp;
    my @match = grep {/\b$_\b/s} @lines;
    print @match;
    }

我仍然缺乏一旦没有输入任何内容或换行符或任何空格字符就会退出的条件。

4

2 回答 2

3
while (<>)

方法

while (defined($_ = <>))

所以需要按 Ctrl-D (unix) 或 Ctrl-Z, Enter (Windows) 来表示输入结束。或者您可以添加一个空行检查:

while (<>) {
   chomp;
   last if $_ eq "";
   print grep /\b$_\b/s, @lines;
}
于 2013-05-20T03:59:12.750 回答
1

您的示例中可能存在问题,my @match = grep {/\b$_\b/s} @lines;因为 grep 不适用于用户输入,而仅适用于@lines. 它的作用是这样的:

grep { $lines[index] =~ /\b$lines[index]\b/s }

你可能想要这个:

while (my $input = <>) {
  chomp($input);
  last if $input =~ /^ \s* $/x; # exit loop if no input or only whitespaces

  my @match = grep { /\b$input\b/s } @lines;
  print @match;
}
于 2013-05-20T06:45:14.303 回答