简体   繁体   English

如何在perl中grep读取文件

[英]How to grep read file in perl

I would like to read a file in perl, after, the user can input any string and grep will try to find the string inputted in the file read. 我想在perl中读取一个文件,之后,用户可以输入任何字符串,grep会尝试查找在文件中输入的字符串读取。 It will only exit when the user input nothing or any space character. 它只会在用户输入任何内容或任何空格字符时退出。 Here's my code which is not working: 这是我的代码不起作用:

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

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

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

I'm still lacking the condition where it will exit once nothing is inputted or a newline or any space character. 我仍然缺乏一旦输入任何内容或换行或任何空格字符就会退出的情况。

while (<>)

means 手段

while (defined($_ = <>))

so need to press Ctrl-D (unix) or Ctrl-Z, Enter (Windows) to signal end of input. 所以需要按Ctrl-D(unix)或Ctrl-Z,Enter(Windows)来指示输入结束。 Or you could add a check for a blank line: 或者您可以添加一个空行检查:

while (<>) {
   chomp;
   last if $_ eq "";
   print grep /\b$_\b/s, @lines;
}

There is possible problem in your example with my @match = grep {/\\b$_\\b/s} @lines; my @match = grep {/\\b$_\\b/s} @lines;您的示例中可能存在问题my @match = grep {/\\b$_\\b/s} @lines; as grep is not working with user input, but only with content of @lines . 因为grep不能处理用户输入,而只能处理@lines内容。 What it does is this: 它的作用是:

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

and you probably want this: 你可能想要这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM