简体   繁体   English

当反斜杠存储在Perl中的数组中时,在正则表达式中不起作用

[英]Backslash not working in regex when stored in an array in Perl

I'm working on a simple lexical analyser for a project and I'm using an array to store regex patterns as strings. 我正在为一个项目开发一个简单的词法分析器,并且正在使用数组将正则表达式模式存储为字符串。

I test each regex pattern individually to make sure I get the correct output when checking a line of a file. 我分别测试每个正则表达式模式,以确保检查文件行时得到正确的输出。

The problem is, once I stored these strings in an array I started getting several errors. 问题是,一旦我将这些字符串存储在数组中,我就会开始遇到一些错误。 Mainly when searching for strings that start with backslash \\ . 主要是在搜索以反斜杠\\开头的字符串时。

This is my Perl code 这是我的Perl代码

#!/usr/bin/perl

@PATTERNS = ("\\begin", "\\end", "{", "}", "<\d+(\.\d+)?>", "<p>", "<\\p>", ".*", "%%+", "<%", "%>") ;

print "Enter some text: ";
chomp( $input = <> );

print test();

sub test() {

    my $arrSize = @PATTERNS;

    for ( my $i = 0; $i < $arrSize; $i++ ) {

        if ( $input =~ /$PATTERNS[$i]/gi ) {
            print "good input\n";
        }
        else {
            print "bad input\n";
        }
    }

}

This above is my test file to read lines I manually type in to check regex expression and give me a good input if it matches or bad input if it doesn't. 上面是我的测试文件,用于读取我手动键入以检查regex表达式的行,如果匹配则给我一个好的输入,否则就给我一个不好的输入。

Perl continues to skip over my backslashes no matter how I use it in each string. 不管我如何在每个字符串中使用Perl,Perl都会继续跳过我的反斜杠。

I'm using the default Perl v5.18.2 that is installed with Ubuntu 14.04. 我正在使用随Ubuntu 14.04一起安装的默认Perl v5.18.2。

Strings in double quotes are "interpolated" in Perl. 双引号中的字符串在Perl中“内插”。 Backslash has a special meaning here. 反斜杠在这里具有特殊含义。 If you want to store regular expressions in an array, it's better to use the qr// construct: 如果要将正则表达式存储在数组中,最好使用qr//构造:

my @PATTERNS = ( qr/\\begin/,
                 qr/\\end/,
                 qr/{/,
                 qr/}/,
                 qr/<\d+(\.\d+)?>/,
                 qr/<p>/,
                 qr(</p>), # I assumed HTML/PHP, so replaced \p.
                 qr/.*/,
                 qr/%%+/,
                 qr/<%/,
                 qr/%>/,
               ) ;

You should use warnings , they would warn you against some mistakes you made: 您应该使用警告 ,它们会警告您一些错误:

Unrecognized escape \d passed through at /home/choroba/1.pl line 5.
Unrecognized escape \d passed through at /home/choroba/1.pl line 5.
main::test() called too early to check prototype at /home/choroba/1.pl line 10.

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

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