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
#!/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.
Perl continues to skip over my backslashes no matter how I use it in each string.
I'm using the default Perl v5.18.2 that is installed with Ubuntu 14.04.
Strings in double quotes are "interpolated" in 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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.