2011-02-17 27 views

回答

0

哦,想通了怎么做。原来很简单 但是,如果我不想让搜索区分大小写,我该怎么办?

print "Name: "; 
my $string = <>; 

open FILE, "test.txt" or die $!; 

while(<FILE>) { 
    chomp; 
    print "$_\n" if(/$string*/); 
} 
close FILE; 
+1

您应该添加一个`我`对模式匹配运算符:`/ $ string */i`。 – 2011-02-17 05:03:24

+1

你也可能想`chomp $ string` – 2011-02-17 05:08:43

+0

如果你想让程序更加简洁,用`print grep {/ $ string/i} `替换循环。请参阅:[perlretut](http://perldoc.perl.org/perlretut.html)和[perlre](http://perldoc.perl.org/perlre.html)。 – 2011-02-17 05:09:15

1

您添加的正则表达式修改器的 “i”

print "Name: "; 
my $string = <>; 

open FILE, "test.txt" or die $!; 

while(<FILE>) { 
    chomp; 
    print "$_\n" if(/$string*/i); 
} 
close FILE; 
0

一个内胆:

perl -nE 'BEGIN{$pattern=shift};say if /$pattern/i' pattern filename(s) 

perl -nE 'BEGIN{$pattern=shift};say "$ARGV $.: $_" if /$pattern/i' pattern filename(s) 

获取文件和行号了。

0

你的while循环体有点复杂。这也适用于:

while (<FILE>) { print if /$string/i } 

有没有必要终日啃食换行符,然后重新添加它

5

有这个回答两个不同的概念:

  1. 文件IO,并通过迭代所有行在一段时间内
  2. 正则表达式,特别是将一个变量传递给正则表达式。

请注意使用quotemeta。当用户输入包含RE特定字符时(如果不处理它,甚至可能会创建一个illigel RE),这很重要。

下面是代码:

print "Looking for: "; 
my $input = <>; 
chomp $input; 
my $re = quotemeta $input; 

open my $fh, "<", "myfile.txt" or die $!; 
while(<$fh>) { 
    print if /$re/; 
} 
close $fh;