是否可以使用变量匹配正则表达式?

时间:2017-08-10 05:01:57

标签: regex perl

这是我的代码

my $filename = 'text.log';

my $items = "donkey";

open(my $fh, '<:encoding(UTF-8)', $filename) or die "Cant open";

while (my $contents = <$fh>)
{
        print "$contents";

        if ( $items =~m/$contents/)             
             { print "Found $contents";}            
        else { print "NOTHING\n";}
}

1 个答案:

答案 0 :(得分:1)

是的,但您需要删除每行($contents =~ s/\n$//;)上的尾随新闻空间:

#!/usr/bin/env perl
my $filename = 'text.log';
my $items = "donkey";
open(my $fh, '<:encoding(UTF-8)', $filename) or die "Cant open";
while (my $contents = <$fh>) {
    print "$contents";
    $contents =~ s/\n$//;
    if ($items =~ m/$contents/) {
        print "Found $contents\n";
    } else {
        print "NOTHING\n";
    }
}

测试:

$ cat text.log 
test
ok
donk
$ ./test.pl 
test
NOTHING
ok
NOTHING
donk
Found donk