尝试匹配两个在Perl中都包含特殊字符的变量

时间:2016-05-18 04:09:54

标签: regex perl

所以这是一个奇怪的问题。我有很多脚本由" master"执行。脚本,我需要验证" master"中的内容。已验证。问题是,这些脚本包含特殊字符,我需要匹配它们以确保" Master"正在引用正确的脚本。

一个文件的示例可能是

Example's of file names (20160517) [test].sh

这是我的代码的样子。 @MasterScipt是一个数组,其中每个元素都是我期望命名子脚本的文件名。

opendir( DURR, $FileLocation );    # I'm looking in a directory where the subscripts reside

foreach ( readdir(DURR) ) {

    for ( my $j = 0; $j != $MasterScriptlength; $j++ ) {
        $MasterScipt[$j] =~ s/\r//g;
        print "DARE TO COMPARE\n";
        print "$MasterScipt[$j]\n";
        print "$_\n";

        #I added the \Q to quotemeta, but I think the issue is with $_
        #I've tried variations like
        #if(quotemeta($_) =~/\Q$MasterScipt[$j]/){
        #To no avail, I also tried using eq operator and no luck :(
        if ( $_ =~ /\Q$MasterScipt[$j]/ ) {
            print "WE GOOD VINCENT\n";
        }
    }
}

closedir(DURR);

无论我做什么,我的输出总是看起来像这样

DARE TO COMPARE
Example's of file names (20160517) [test].sh
Example's of file names (20160517) [test].sh

2 个答案:

答案 0 :(得分:2)

好吧,我盯着这个东西太久了,我想写出这个问题帮我回答了。

我不仅需要在我的正则表达式中添加\Q,而且还有一个空格字符。我对chomp$_都进行了$MasterScipt[$j],现在已经开始工作了。

答案 1 :(得分:1)

我建议你的代码应该更像这样。主要的变化是我使用命名变量$file作为readdir返回的值,并迭代数组@MasterScipt内容而不是它的索引是因为$j从不在你自己的代码中使用,除了访问数组元素

s/\s+\z// for @MasterScipt;

opendir DURR, $FileLocation or die qq{Unable to open directory "$FileLocation": $!};

while ( my $file = readdir DURR ) {

    for my $pattern ( @MasterScipt ) {

        print "DARE TO COMPARE\n";
        print "$pattern\n";
        print "$file\n";

        if ( $file =~ /\Q$pattern/ ) {
            print "WE GOOD VINCENT\n";
        }
    }
}

closedir(DURR);

但这是一个简单的grep操作,它可以这样编写。此备选方案构建一个正则表达式,该表达式将匹配@MasterScipt中的任何项目,并使用grep构建与readdir匹配的所有值的列表

s/\s+\z// for @MasterScipt;

my @matches = do {

    my $re = join '|', map quotemeta, @MasterScipt;

    opendir my $dh, $FileLocation or die qq{Unable to open directory "$FileLocation": $!};

    grep { /$re/ } readdir $dh;
};
相关问题