Know the difference between regex and match operator flags

The match and substitution operators, as well as regex quoting with qr//, use flags to signal certain behavior of the match or interpretation of the pattern.

The flags that change the interpretation of the pattern are listed in the documentation for qr// in perlop (and maybe in other places in earlier versions of the documentation):

Flag Description
i Letters are case-insensitive
m ^ and $ anchors can also match around newlines. This is often called “multi-line mode”.
o Compile pattern only once.
p Capture per-match variables into ${^PREMATCH}, ${MATCH}, and ${^POSTMATCH} instead of the performance-dampening versions.
s The . can match a newline. This is often called “single-line mode”.
x Ignore comments and literal space in the pattern.

When you stringify a regex reference, you can see which flags you set:

use 5.010;

say qr/abc/pi;

The flags immediately after the (? but before the - are enabled, while the remaining flags are disabled:

(?pi-xsm:abc)

You can also use these flags directly in your pattern using the same (?flags:pattern) structure. The flags then only apply to the portion of the pattern in the containing (?...), except for /p with affects the entire pattern. In this example, you make only a portion of the pattern case-insenstive:

use 5.010;

my $pattern = qr/a(?i:b)c/;

foreach ( qw( abc aBc abC Abc ) )
	(
	say "$_ --> ",  do {
		if( /$pattern/ ) { 'Matched' }
		else             { 'No match' }
		};
	)

The output shows you that the pattern matched the b without regard to case, but the other letters matched exactly the case in the literal pattern:

abc --> Matched
aBc --> Matched
abC --> No match
Abc --> No match

With the m// and s/// operators, you can specify any of the pattern flags, as well as some of the operation flags. However, you cannot specify these flags with regex quoting since they only apply to the operators:

Flag Description
c Don’t reset search position after a failed match. This only works when you also use /g.
g Match in global mode, keeping track of the match position.
e eval the substitution replacement before replacing it (s/// only)

In summary, here are the flags and when you can use them:

Pattern flags Operator flags
i, m, o, p, s, x c, g, e
Use with qr//, (?…), m//, and s/// Use with m//, s///
Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]

7ads6x98y