This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlapi: Consolidate sv_catpv-ish entries
[perl5.git] / pod / perlretut.pod
1 =head1 NAME
2
3 perlretut - Perl regular expressions tutorial
4
5 =head1 DESCRIPTION
6
7 This page provides a basic tutorial on understanding, creating and
8 using regular expressions in Perl.  It serves as a complement to the
9 reference page on regular expressions L<perlre>.  Regular expressions
10 are an integral part of the C<m//>, C<s///>, C<qr//> and C<split>
11 operators and so this tutorial also overlaps with
12 L<perlop/"Regexp Quote-Like Operators"> and L<perlfunc/split>.
13
14 Perl is widely renowned for excellence in text processing, and regular
15 expressions are one of the big factors behind this fame.  Perl regular
16 expressions display an efficiency and flexibility unknown in most
17 other computer languages.  Mastering even the basics of regular
18 expressions will allow you to manipulate text with surprising ease.
19
20 What is a regular expression?  At its most basic, a regular expression
21 is a template that is used to determine if a string has certain
22 characteristics.  The string is most often some text, such as a line,
23 sentence, web page, or even a whole book, but less commonly it could be
24 some binary data as well.
25 Suppose we want to determine if the text in variable, C<$var> contains
26 the sequence of characters S<C<m u s h r o o m>>
27 (blanks added for legibility).  We can write in Perl
28
29  $var =~ m/mushroom/
30
31 The value of this expression will be TRUE if C<$var> contains that
32 sequence of characters, and FALSE otherwise.  The portion enclosed in
33 C<'E<sol>'> characters denotes the characteristic we are looking for.
34 We use the term I<pattern> for it.  The process of looking to see if the
35 pattern occurs in the string is called I<matching>, and the C<"=~">
36 operator along with the C<m//> tell Perl to try to match the pattern
37 against the string.  Note that the pattern is also a string, but a very
38 special kind of one, as we will see.  Patterns are in common use these
39 days;
40 examples are the patterns typed into a search engine to find web pages
41 and the patterns used to list files in a directory, I<e.g.>, "C<ls *.txt>"
42 or "C<dir *.*>".  In Perl, the patterns described by regular expressions
43 are used not only to search strings, but to also extract desired parts
44 of strings, and to do search and replace operations.
45
46 Regular expressions have the undeserved reputation of being abstract
47 and difficult to understand.  This really stems simply because the
48 notation used to express them tends to be terse and dense, and not
49 because of inherent complexity.  We recommend using the C</x> regular
50 expression modifier (described below) along with plenty of white space
51 to make them less dense, and easier to read.  Regular expressions are
52 constructed using
53 simple concepts like conditionals and loops and are no more difficult
54 to understand than the corresponding C<if> conditionals and C<while>
55 loops in the Perl language itself.
56
57 This tutorial flattens the learning curve by discussing regular
58 expression concepts, along with their notation, one at a time and with
59 many examples.  The first part of the tutorial will progress from the
60 simplest word searches to the basic regular expression concepts.  If
61 you master the first part, you will have all the tools needed to solve
62 about 98% of your needs.  The second part of the tutorial is for those
63 comfortable with the basics and hungry for more power tools.  It
64 discusses the more advanced regular expression operators and
65 introduces the latest cutting-edge innovations.
66
67 A note: to save time, "regular expression" is often abbreviated as
68 regexp or regex.  Regexp is a more natural abbreviation than regex, but
69 is harder to pronounce.  The Perl pod documentation is evenly split on
70 regexp vs regex; in Perl, there is more than one way to abbreviate it.
71 We'll use regexp in this tutorial.
72
73 New in v5.22, L<C<use re 'strict'>|re/'strict' mode> applies stricter
74 rules than otherwise when compiling regular expression patterns.  It can
75 find things that, while legal, may not be what you intended.
76
77 =head1 Part 1: The basics
78
79 =head2 Simple word matching
80
81 The simplest regexp is simply a word, or more generally, a string of
82 characters.  A regexp consisting of just a word matches any string that
83 contains that word:
84
85     "Hello World" =~ /World/;  # matches
86
87 What is this Perl statement all about? C<"Hello World"> is a simple
88 double-quoted string.  C<World> is the regular expression and the
89 C<//> enclosing C</World/> tells Perl to search a string for a match.
90 The operator C<=~> associates the string with the regexp match and
91 produces a true value if the regexp matched, or false if the regexp
92 did not match.  In our case, C<World> matches the second word in
93 C<"Hello World">, so the expression is true.  Expressions like this
94 are useful in conditionals:
95
96     if ("Hello World" =~ /World/) {
97         print "It matches\n";
98     }
99     else {
100         print "It doesn't match\n";
101     }
102
103 There are useful variations on this theme.  The sense of the match can
104 be reversed by using the C<!~> operator:
105
106     if ("Hello World" !~ /World/) {
107         print "It doesn't match\n";
108     }
109     else {
110         print "It matches\n";
111     }
112
113 The literal string in the regexp can be replaced by a variable:
114
115     my $greeting = "World";
116     if ("Hello World" =~ /$greeting/) {
117         print "It matches\n";
118     }
119     else {
120         print "It doesn't match\n";
121     }
122
123 If you're matching against the special default variable C<$_>, the
124 C<$_ =~> part can be omitted:
125
126     $_ = "Hello World";
127     if (/World/) {
128         print "It matches\n";
129     }
130     else {
131         print "It doesn't match\n";
132     }
133
134 And finally, the C<//> default delimiters for a match can be changed
135 to arbitrary delimiters by putting an C<'m'> out front:
136
137     "Hello World" =~ m!World!;   # matches, delimited by '!'
138     "Hello World" =~ m{World};   # matches, note the matching '{}'
139     "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
140                                  # '/' becomes an ordinary char
141
142 C</World/>, C<m!World!>, and C<m{World}> all represent the
143 same thing.  When, I<e.g.>, the quote (C<'"'>) is used as a delimiter, the forward
144 slash C<'/'> becomes an ordinary character and can be used in this regexp
145 without trouble.
146
147 Let's consider how different regexps would match C<"Hello World">:
148
149     "Hello World" =~ /world/;  # doesn't match
150     "Hello World" =~ /o W/;    # matches
151     "Hello World" =~ /oW/;     # doesn't match
152     "Hello World" =~ /World /; # doesn't match
153
154 The first regexp C<world> doesn't match because regexps are
155 case-sensitive.  The second regexp matches because the substring
156 S<C<'o W'>> occurs in the string S<C<"Hello World">>.  The space
157 character C<' '> is treated like any other character in a regexp and is
158 needed to match in this case.  The lack of a space character is the
159 reason the third regexp C<'oW'> doesn't match.  The fourth regexp
160 "C<World >" doesn't match because there is a space at the end of the
161 regexp, but not at the end of the string.  The lesson here is that
162 regexps must match a part of the string I<exactly> in order for the
163 statement to be true.
164
165 If a regexp matches in more than one place in the string, Perl will
166 always match at the earliest possible point in the string:
167
168     "Hello World" =~ /o/;       # matches 'o' in 'Hello'
169     "That hat is red" =~ /hat/; # matches 'hat' in 'That'
170
171 With respect to character matching, there are a few more points you
172 need to know about.   First of all, not all characters can be used "as
173 is" in a match.  Some characters, called I<metacharacters>, are
174 generally reserved for use in regexp notation.  The metacharacters are
175
176     {}[]()^$.|*+?-#\
177
178 This list is not as definitive as it may appear (or be claimed to be in
179 other documentation).  For example, C<"#"> is a metacharacter only when
180 the C</x> pattern modifier (described below) is used, and both C<"}">
181 and C<"]"> are metacharacters only when paired with opening C<"{"> or
182 C<"["> respectively; other gotchas apply.
183
184 The significance of each of these will be explained
185 in the rest of the tutorial, but for now, it is important only to know
186 that a metacharacter can be matched as-is by putting a backslash before
187 it:
188
189     "2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
190     "2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +
191     "The interval is [0,1)." =~ /[0,1)./     # is a syntax error!
192     "The interval is [0,1)." =~ /\[0,1\)\./  # matches
193     "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/;  # matches
194
195 In the last regexp, the forward slash C<'/'> is also backslashed,
196 because it is used to delimit the regexp.  This can lead to LTS
197 (leaning toothpick syndrome), however, and it is often more readable
198 to change delimiters.
199
200     "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!;  # easier to read
201
202 The backslash character C<'\'> is a metacharacter itself and needs to
203 be backslashed:
204
205     'C:\WIN32' =~ /C:\\WIN/;   # matches
206
207 In situations where it doesn't make sense for a particular metacharacter
208 to mean what it normally does, it automatically loses its
209 metacharacter-ness and becomes an ordinary character that is to be
210 matched literally.  For example, the C<'}'> is a metacharacter only when
211 it is the mate of a C<'{'> metacharacter.  Otherwise it is treated as a
212 literal RIGHT CURLY BRACKET.  This may lead to unexpected results.
213 L<C<use re 'strict'>|re/'strict' mode> can catch some of these.
214
215 In addition to the metacharacters, there are some ASCII characters
216 which don't have printable character equivalents and are instead
217 represented by I<escape sequences>.  Common examples are C<\t> for a
218 tab, C<\n> for a newline, C<\r> for a carriage return and C<\a> for a
219 bell (or alert).  If your string is better thought of as a sequence of arbitrary
220 bytes, the octal escape sequence, I<e.g.>, C<\033>, or hexadecimal escape
221 sequence, I<e.g.>, C<\x1B> may be a more natural representation for your
222 bytes.  Here are some examples of escapes:
223
224     "1000\t2000" =~ m(0\t2)   # matches
225     "1000\n2000" =~ /0\n20/   # matches
226     "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
227     "cat"   =~ /\o{143}\x61\x74/ # matches in ASCII, but a weird way
228                                  # to spell cat
229
230 If you've been around Perl a while, all this talk of escape sequences
231 may seem familiar.  Similar escape sequences are used in double-quoted
232 strings and in fact the regexps in Perl are mostly treated as
233 double-quoted strings.  This means that variables can be used in
234 regexps as well.  Just like double-quoted strings, the values of the
235 variables in the regexp will be substituted in before the regexp is
236 evaluated for matching purposes.  So we have:
237
238     $foo = 'house';
239     'housecat' =~ /$foo/;      # matches
240     'cathouse' =~ /cat$foo/;   # matches
241     'housecat' =~ /${foo}cat/; # matches
242
243 So far, so good.  With the knowledge above you can already perform
244 searches with just about any literal string regexp you can dream up.
245 Here is a I<very simple> emulation of the Unix grep program:
246
247     % cat > simple_grep
248     #!/usr/bin/perl
249     $regexp = shift;
250     while (<>) {
251         print if /$regexp/;
252     }
253     ^D
254
255     % chmod +x simple_grep
256
257     % simple_grep abba /usr/dict/words
258     Babbage
259     cabbage
260     cabbages
261     sabbath
262     Sabbathize
263     Sabbathizes
264     sabbatical
265     scabbard
266     scabbards
267
268 This program is easy to understand.  C<#!/usr/bin/perl> is the standard
269 way to invoke a perl program from the shell.
270 S<C<$regexp = shift;>> saves the first command line argument as the
271 regexp to be used, leaving the rest of the command line arguments to
272 be treated as files.  S<C<< while (<>) >>> loops over all the lines in
273 all the files.  For each line, S<C<print if /$regexp/;>> prints the
274 line if the regexp matches the line.  In this line, both C<print> and
275 C</$regexp/> use the default variable C<$_> implicitly.
276
277 With all of the regexps above, if the regexp matched anywhere in the
278 string, it was considered a match.  Sometimes, however, we'd like to
279 specify I<where> in the string the regexp should try to match.  To do
280 this, we would use the I<anchor> metacharacters C<'^'> and C<'$'>.  The
281 anchor C<'^'> means match at the beginning of the string and the anchor
282 C<'$'> means match at the end of the string, or before a newline at the
283 end of the string.  Here is how they are used:
284
285     "housekeeper" =~ /keeper/;    # matches
286     "housekeeper" =~ /^keeper/;   # doesn't match
287     "housekeeper" =~ /keeper$/;   # matches
288     "housekeeper\n" =~ /keeper$/; # matches
289
290 The second regexp doesn't match because C<'^'> constrains C<keeper> to
291 match only at the beginning of the string, but C<"housekeeper"> has
292 keeper starting in the middle.  The third regexp does match, since the
293 C<'$'> constrains C<keeper> to match only at the end of the string.
294
295 When both C<'^'> and C<'$'> are used at the same time, the regexp has to
296 match both the beginning and the end of the string, I<i.e.>, the regexp
297 matches the whole string.  Consider
298
299     "keeper" =~ /^keep$/;      # doesn't match
300     "keeper" =~ /^keeper$/;    # matches
301     ""       =~ /^$/;          # ^$ matches an empty string
302
303 The first regexp doesn't match because the string has more to it than
304 C<keep>.  Since the second regexp is exactly the string, it
305 matches.  Using both C<'^'> and C<'$'> in a regexp forces the complete
306 string to match, so it gives you complete control over which strings
307 match and which don't.  Suppose you are looking for a fellow named
308 bert, off in a string by himself:
309
310     "dogbert" =~ /bert/;   # matches, but not what you want
311
312     "dilbert" =~ /^bert/;  # doesn't match, but ..
313     "bertram" =~ /^bert/;  # matches, so still not good enough
314
315     "bertram" =~ /^bert$/; # doesn't match, good
316     "dilbert" =~ /^bert$/; # doesn't match, good
317     "bert"    =~ /^bert$/; # matches, perfect
318
319 Of course, in the case of a literal string, one could just as easily
320 use the string comparison S<C<$string eq 'bert'>> and it would be
321 more efficient.   The  C<^...$> regexp really becomes useful when we
322 add in the more powerful regexp tools below.
323
324 =head2 Using character classes
325
326 Although one can already do quite a lot with the literal string
327 regexps above, we've only scratched the surface of regular expression
328 technology.  In this and subsequent sections we will introduce regexp
329 concepts (and associated metacharacter notations) that will allow a
330 regexp to represent not just a single character sequence, but a I<whole
331 class> of them.
332
333 One such concept is that of a I<character class>.  A character class
334 allows a set of possible characters, rather than just a single
335 character, to match at a particular point in a regexp.  You can define
336 your own custom character classes.  These
337 are denoted by brackets C<[...]>, with the set of characters
338 to be possibly matched inside.  Here are some examples:
339
340     /cat/;       # matches 'cat'
341     /[bcr]at/;   # matches 'bat, 'cat', or 'rat'
342     /item[0123456789]/;  # matches 'item0' or ... or 'item9'
343     "abc" =~ /[cab]/;    # matches 'a'
344
345 In the last statement, even though C<'c'> is the first character in
346 the class, C<'a'> matches because the first character position in the
347 string is the earliest point at which the regexp can match.
348
349     /[yY][eE][sS]/;      # match 'yes' in a case-insensitive way
350                          # 'yes', 'Yes', 'YES', etc.
351
352 This regexp displays a common task: perform a case-insensitive
353 match.  Perl provides a way of avoiding all those brackets by simply
354 appending an C<'i'> to the end of the match.  Then C</[yY][eE][sS]/;>
355 can be rewritten as C</yes/i;>.  The C<'i'> stands for
356 case-insensitive and is an example of a I<modifier> of the matching
357 operation.  We will meet other modifiers later in the tutorial.
358
359 We saw in the section above that there were ordinary characters, which
360 represented themselves, and special characters, which needed a
361 backslash C<'\'> to represent themselves.  The same is true in a
362 character class, but the sets of ordinary and special characters
363 inside a character class are different than those outside a character
364 class.  The special characters for a character class are C<-]\^$> (and
365 the pattern delimiter, whatever it is).
366 C<']'> is special because it denotes the end of a character class.  C<'$'> is
367 special because it denotes a scalar variable.  C<'\'> is special because
368 it is used in escape sequences, just like above.  Here is how the
369 special characters C<]$\> are handled:
370
371    /[\]c]def/; # matches ']def' or 'cdef'
372    $x = 'bcr';
373    /[$x]at/;   # matches 'bat', 'cat', or 'rat'
374    /[\$x]at/;  # matches '$at' or 'xat'
375    /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
376
377 The last two are a little tricky.  In C<[\$x]>, the backslash protects
378 the dollar sign, so the character class has two members C<'$'> and C<'x'>.
379 In C<[\\$x]>, the backslash is protected, so C<$x> is treated as a
380 variable and substituted in double quote fashion.
381
382 The special character C<'-'> acts as a range operator within character
383 classes, so that a contiguous set of characters can be written as a
384 range.  With ranges, the unwieldy C<[0123456789]> and C<[abc...xyz]>
385 become the svelte C<[0-9]> and C<[a-z]>.  Some examples are
386
387     /item[0-9]/;  # matches 'item0' or ... or 'item9'
388     /[0-9bx-z]aa/;  # matches '0aa', ..., '9aa',
389                     # 'baa', 'xaa', 'yaa', or 'zaa'
390     /[0-9a-fA-F]/;  # matches a hexadecimal digit
391     /[0-9a-zA-Z_]/; # matches a "word" character,
392                     # like those in a Perl variable name
393
394 If C<'-'> is the first or last character in a character class, it is
395 treated as an ordinary character; C<[-ab]>, C<[ab-]> and C<[a\-b]> are
396 all equivalent.
397
398 The special character C<'^'> in the first position of a character class
399 denotes a I<negated character class>, which matches any character but
400 those in the brackets.  Both C<[...]> and C<[^...]> must match a
401 character, or the match fails.  Then
402
403     /[^a]at/;  # doesn't match 'aat' or 'at', but matches
404                # all other 'bat', 'cat, '0at', '%at', etc.
405     /[^0-9]/;  # matches a non-numeric character
406     /[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary
407
408 Now, even C<[0-9]> can be a bother to write multiple times, so in the
409 interest of saving keystrokes and making regexps more readable, Perl
410 has several abbreviations for common character classes, as shown below.
411 Since the introduction of Unicode, unless the C</a> modifier is in
412 effect, these character classes match more than just a few characters in
413 the ASCII range.
414
415 =over 4
416
417 =item *
418
419 C<\d> matches a digit, not just C<[0-9]> but also digits from non-roman scripts
420
421 =item *
422
423 C<\s> matches a whitespace character, the set C<[\ \t\r\n\f]> and others
424
425 =item *
426
427 C<\w> matches a word character (alphanumeric or C<'_'>), not just C<[0-9a-zA-Z_]>
428 but also digits and characters from non-roman scripts
429
430 =item *
431
432 C<\D> is a negated C<\d>; it represents any other character than a digit, or C<[^\d]>
433
434 =item *
435
436 C<\S> is a negated C<\s>; it represents any non-whitespace character C<[^\s]>
437
438 =item *
439
440 C<\W> is a negated C<\w>; it represents any non-word character C<[^\w]>
441
442 =item *
443
444 The period C<'.'> matches any character but C<"\n"> (unless the modifier C</s> is
445 in effect, as explained below).
446
447 =item *
448
449 C<\N>, like the period, matches any character but C<"\n">, but it does so
450 regardless of whether the modifier C</s> is in effect.
451
452 =back
453
454 The C</a> modifier, available starting in Perl 5.14,  is used to
455 restrict the matches of C<\d>, C<\s>, and C<\w> to just those in the ASCII range.
456 It is useful to keep your program from being needlessly exposed to full
457 Unicode (and its accompanying security considerations) when all you want
458 is to process English-like text.  (The "a" may be doubled, C</aa>, to
459 provide even more restrictions, preventing case-insensitive matching of
460 ASCII with non-ASCII characters; otherwise a Unicode "Kelvin Sign"
461 would caselessly match a "k" or "K".)
462
463 The C<\d\s\w\D\S\W> abbreviations can be used both inside and outside
464 of bracketed character classes.  Here are some in use:
465
466     /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
467     /[\d\s]/;         # matches any digit or whitespace character
468     /\w\W\w/;         # matches a word char, followed by a
469                       # non-word char, followed by a word char
470     /..rt/;           # matches any two chars, followed by 'rt'
471     /end\./;          # matches 'end.'
472     /end[.]/;         # same thing, matches 'end.'
473
474 Because a period is a metacharacter, it needs to be escaped to match
475 as an ordinary period. Because, for example, C<\d> and C<\w> are sets
476 of characters, it is incorrect to think of C<[^\d\w]> as C<[\D\W]>; in
477 fact C<[^\d\w]> is the same as C<[^\w]>, which is the same as
478 C<[\W]>. Think DeMorgan's laws.
479
480 In actuality, the period and C<\d\s\w\D\S\W> abbreviations are
481 themselves types of character classes, so the ones surrounded by
482 brackets are just one type of character class.  When we need to make a
483 distinction, we refer to them as "bracketed character classes."
484
485 An anchor useful in basic regexps is the I<word anchor>
486 C<\b>.  This matches a boundary between a word character and a non-word
487 character C<\w\W> or C<\W\w>:
488
489     $x = "Housecat catenates house and cat";
490     $x =~ /cat/;    # matches cat in 'housecat'
491     $x =~ /\bcat/;  # matches cat in 'catenates'
492     $x =~ /cat\b/;  # matches cat in 'housecat'
493     $x =~ /\bcat\b/;  # matches 'cat' at end of string
494
495 Note in the last example, the end of the string is considered a word
496 boundary.
497
498 For natural language processing (so that, for example, apostrophes are
499 included in words), use instead C<\b{wb}>
500
501     "don't" =~ / .+? \b{wb} /x;  # matches the whole string
502
503 You might wonder why C<'.'> matches everything but C<"\n"> - why not
504 every character? The reason is that often one is matching against
505 lines and would like to ignore the newline characters.  For instance,
506 while the string C<"\n"> represents one line, we would like to think
507 of it as empty.  Then
508
509     ""   =~ /^$/;    # matches
510     "\n" =~ /^$/;    # matches, $ anchors before "\n"
511
512     ""   =~ /./;      # doesn't match; it needs a char
513     ""   =~ /^.$/;    # doesn't match; it needs a char
514     "\n" =~ /^.$/;    # doesn't match; it needs a char other than "\n"
515     "a"  =~ /^.$/;    # matches
516     "a\n"  =~ /^.$/;  # matches, $ anchors before "\n"
517
518 This behavior is convenient, because we usually want to ignore
519 newlines when we count and match characters in a line.  Sometimes,
520 however, we want to keep track of newlines.  We might even want C<'^'>
521 and C<'$'> to anchor at the beginning and end of lines within the
522 string, rather than just the beginning and end of the string.  Perl
523 allows us to choose between ignoring and paying attention to newlines
524 by using the C</s> and C</m> modifiers.  C</s> and C</m> stand for
525 single line and multi-line and they determine whether a string is to
526 be treated as one continuous string, or as a set of lines.  The two
527 modifiers affect two aspects of how the regexp is interpreted: 1) how
528 the C<'.'> character class is defined, and 2) where the anchors C<'^'>
529 and C<'$'> are able to match.  Here are the four possible combinations:
530
531 =over 4
532
533 =item *
534
535 no modifiers: Default behavior.  C<'.'> matches any character
536 except C<"\n">.  C<'^'> matches only at the beginning of the string and
537 C<'$'> matches only at the end or before a newline at the end.
538
539 =item *
540
541 s modifier (C</s>): Treat string as a single long line.  C<'.'> matches
542 any character, even C<"\n">.  C<'^'> matches only at the beginning of
543 the string and C<'$'> matches only at the end or before a newline at the
544 end.
545
546 =item *
547
548 m modifier (C</m>): Treat string as a set of multiple lines.  C<'.'>
549 matches any character except C<"\n">.  C<'^'> and C<'$'> are able to match
550 at the start or end of I<any> line within the string.
551
552 =item *
553
554 both s and m modifiers (C</sm>): Treat string as a single long line, but
555 detect multiple lines.  C<'.'> matches any character, even
556 C<"\n">.  C<'^'> and C<'$'>, however, are able to match at the start or end
557 of I<any> line within the string.
558
559 =back
560
561 Here are examples of C</s> and C</m> in action:
562
563     $x = "There once was a girl\nWho programmed in Perl\n";
564
565     $x =~ /^Who/;   # doesn't match, "Who" not at start of string
566     $x =~ /^Who/s;  # doesn't match, "Who" not at start of string
567     $x =~ /^Who/m;  # matches, "Who" at start of second line
568     $x =~ /^Who/sm; # matches, "Who" at start of second line
569
570     $x =~ /girl.Who/;   # doesn't match, "." doesn't match "\n"
571     $x =~ /girl.Who/s;  # matches, "." matches "\n"
572     $x =~ /girl.Who/m;  # doesn't match, "." doesn't match "\n"
573     $x =~ /girl.Who/sm; # matches, "." matches "\n"
574
575 Most of the time, the default behavior is what is wanted, but C</s> and
576 C</m> are occasionally very useful.  If C</m> is being used, the start
577 of the string can still be matched with C<\A> and the end of the string
578 can still be matched with the anchors C<\Z> (matches both the end and
579 the newline before, like C<'$'>), and C<\z> (matches only the end):
580
581     $x =~ /^Who/m;   # matches, "Who" at start of second line
582     $x =~ /\AWho/m;  # doesn't match, "Who" is not at start of string
583
584     $x =~ /girl$/m;  # matches, "girl" at end of first line
585     $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
586
587     $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
588     $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
589
590 We now know how to create choices among classes of characters in a
591 regexp.  What about choices among words or character strings? Such
592 choices are described in the next section.
593
594 =head2 Matching this or that
595
596 Sometimes we would like our regexp to be able to match different
597 possible words or character strings.  This is accomplished by using
598 the I<alternation> metacharacter C<'|'>.  To match C<dog> or C<cat>, we
599 form the regexp C<dog|cat>.  As before, Perl will try to match the
600 regexp at the earliest possible point in the string.  At each
601 character position, Perl will first try to match the first
602 alternative, C<dog>.  If C<dog> doesn't match, Perl will then try the
603 next alternative, C<cat>.  If C<cat> doesn't match either, then the
604 match fails and Perl moves to the next position in the string.  Some
605 examples:
606
607     "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
608     "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"
609
610 Even though C<dog> is the first alternative in the second regexp,
611 C<cat> is able to match earlier in the string.
612
613     "cats"          =~ /c|ca|cat|cats/; # matches "c"
614     "cats"          =~ /cats|cat|ca|c/; # matches "cats"
615
616 Here, all the alternatives match at the first string position, so the
617 first alternative is the one that matches.  If some of the
618 alternatives are truncations of the others, put the longest ones first
619 to give them a chance to match.
620
621     "cab" =~ /a|b|c/ # matches "c"
622                      # /a|b|c/ == /[abc]/
623
624 The last example points out that character classes are like
625 alternations of characters.  At a given character position, the first
626 alternative that allows the regexp match to succeed will be the one
627 that matches.
628
629 =head2 Grouping things and hierarchical matching
630
631 Alternation allows a regexp to choose among alternatives, but by
632 itself it is unsatisfying.  The reason is that each alternative is a whole
633 regexp, but sometime we want alternatives for just part of a
634 regexp.  For instance, suppose we want to search for housecats or
635 housekeepers.  The regexp C<housecat|housekeeper> fits the bill, but is
636 inefficient because we had to type C<house> twice.  It would be nice to
637 have parts of the regexp be constant, like C<house>, and some
638 parts have alternatives, like C<cat|keeper>.
639
640 The I<grouping> metacharacters C<()> solve this problem.  Grouping
641 allows parts of a regexp to be treated as a single unit.  Parts of a
642 regexp are grouped by enclosing them in parentheses.  Thus we could solve
643 the C<housecat|housekeeper> by forming the regexp as
644 C<house(cat|keeper)>.  The regexp C<house(cat|keeper)> means match
645 C<house> followed by either C<cat> or C<keeper>.  Some more examples
646 are
647
648     /(a|b)b/;    # matches 'ab' or 'bb'
649     /(ac|b)b/;   # matches 'acb' or 'bb'
650     /(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere
651     /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
652
653     /house(cat|)/;  # matches either 'housecat' or 'house'
654     /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
655                         # 'house'.  Note groups can be nested.
656
657     /(19|20|)\d\d/;  # match years 19xx, 20xx, or the Y2K problem, xx
658     "20" =~ /(19|20|)\d\d/;  # matches the null alternative '()\d\d',
659                              # because '20\d\d' can't match
660
661 Alternations behave the same way in groups as out of them: at a given
662 string position, the leftmost alternative that allows the regexp to
663 match is taken.  So in the last example at the first string position,
664 C<"20"> matches the second alternative, but there is nothing left over
665 to match the next two digits C<\d\d>.  So Perl moves on to the next
666 alternative, which is the null alternative and that works, since
667 C<"20"> is two digits.
668
669 The process of trying one alternative, seeing if it matches, and
670 moving on to the next alternative, while going back in the string
671 from where the previous alternative was tried, if it doesn't, is called
672 I<backtracking>.  The term "backtracking" comes from the idea that
673 matching a regexp is like a walk in the woods.  Successfully matching
674 a regexp is like arriving at a destination.  There are many possible
675 trailheads, one for each string position, and each one is tried in
676 order, left to right.  From each trailhead there may be many paths,
677 some of which get you there, and some which are dead ends.  When you
678 walk along a trail and hit a dead end, you have to backtrack along the
679 trail to an earlier point to try another trail.  If you hit your
680 destination, you stop immediately and forget about trying all the
681 other trails.  You are persistent, and only if you have tried all the
682 trails from all the trailheads and not arrived at your destination, do
683 you declare failure.  To be concrete, here is a step-by-step analysis
684 of what Perl does when it tries to match the regexp
685
686     "abcde" =~ /(abd|abc)(df|d|de)/;
687
688 =over 4
689
690 =item Z<>0. Start with the first letter in the string C<'a'>.
691
692 E<nbsp>
693
694 =item Z<>1. Try the first alternative in the first group C<'abd'>.
695
696 E<nbsp>
697
698 =item Z<>2.  Match C<'a'> followed by C<'b'>. So far so good.
699
700 E<nbsp>
701
702 =item Z<>3.  C<'d'> in the regexp doesn't match C<'c'> in the string - a
703 dead end.  So backtrack two characters and pick the second alternative
704 in the first group C<'abc'>.
705
706 E<nbsp>
707
708 =item Z<>4.  Match C<'a'> followed by C<'b'> followed by C<'c'>.  We are on a roll
709 and have satisfied the first group. Set C<$1> to C<'abc'>.
710
711 E<nbsp>
712
713 =item Z<>5 Move on to the second group and pick the first alternative C<'df'>.
714
715 E<nbsp>
716
717 =item Z<>6 Match the C<'d'>.
718
719 E<nbsp>
720
721 =item Z<>7.  C<'f'> in the regexp doesn't match C<'e'> in the string, so a dead
722 end.  Backtrack one character and pick the second alternative in the
723 second group C<'d'>.
724
725 E<nbsp>
726
727 =item Z<>8.  C<'d'> matches. The second grouping is satisfied, so set
728 C<$2> to C<'d'>.
729
730 E<nbsp>
731
732 =item Z<>9.  We are at the end of the regexp, so we are done! We have
733 matched C<'abcd'> out of the string C<"abcde">.
734
735 =back
736
737 There are a couple of things to note about this analysis.  First, the
738 third alternative in the second group C<'de'> also allows a match, but we
739 stopped before we got to it - at a given character position, leftmost
740 wins.  Second, we were able to get a match at the first character
741 position of the string C<'a'>.  If there were no matches at the first
742 position, Perl would move to the second character position C<'b'> and
743 attempt the match all over again.  Only when all possible paths at all
744 possible character positions have been exhausted does Perl give
745 up and declare S<C<$string =~ /(abd|abc)(df|d|de)/;>> to be false.
746
747 Even with all this work, regexp matching happens remarkably fast.  To
748 speed things up, Perl compiles the regexp into a compact sequence of
749 opcodes that can often fit inside a processor cache.  When the code is
750 executed, these opcodes can then run at full throttle and search very
751 quickly.
752
753 =head2 Extracting matches
754
755 The grouping metacharacters C<()> also serve another completely
756 different function: they allow the extraction of the parts of a string
757 that matched.  This is very useful to find out what matched and for
758 text processing in general.  For each grouping, the part that matched
759 inside goes into the special variables C<$1>, C<$2>, I<etc>.  They can be
760 used just as ordinary variables:
761
762     # extract hours, minutes, seconds
763     if ($time =~ /(\d\d):(\d\d):(\d\d)/) {    # match hh:mm:ss format
764         $hours = $1;
765         $minutes = $2;
766         $seconds = $3;
767     }
768
769 Now, we know that in scalar context,
770 S<C<$time =~ /(\d\d):(\d\d):(\d\d)/>> returns a true or false
771 value.  In list context, however, it returns the list of matched values
772 C<($1,$2,$3)>.  So we could write the code more compactly as
773
774     # extract hours, minutes, seconds
775     ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
776
777 If the groupings in a regexp are nested, C<$1> gets the group with the
778 leftmost opening parenthesis, C<$2> the next opening parenthesis,
779 I<etc>.  Here is a regexp with nested groups:
780
781     /(ab(cd|ef)((gi)|j))/;
782      1  2      34
783
784 If this regexp matches, C<$1> contains a string starting with
785 C<'ab'>, C<$2> is either set to C<'cd'> or C<'ef'>, C<$3> equals either
786 C<'gi'> or C<'j'>, and C<$4> is either set to C<'gi'>, just like C<$3>,
787 or it remains undefined.
788
789 For convenience, Perl sets C<$+> to the string held by the highest numbered
790 C<$1>, C<$2>,... that got assigned (and, somewhat related, C<$^N> to the
791 value of the C<$1>, C<$2>,... most-recently assigned; I<i.e.> the C<$1>,
792 C<$2>,... associated with the rightmost closing parenthesis used in the
793 match).
794
795
796 =head2 Backreferences
797
798 Closely associated with the matching variables C<$1>, C<$2>, ... are
799 the I<backreferences> C<\g1>, C<\g2>,...  Backreferences are simply
800 matching variables that can be used I<inside> a regexp.  This is a
801 really nice feature; what matches later in a regexp is made to depend on
802 what matched earlier in the regexp.  Suppose we wanted to look
803 for doubled words in a text, like "the the".  The following regexp finds
804 all 3-letter doubles with a space in between:
805
806     /\b(\w\w\w)\s\g1\b/;
807
808 The grouping assigns a value to C<\g1>, so that the same 3-letter sequence
809 is used for both parts.
810
811 A similar task is to find words consisting of two identical parts:
812
813     % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\g1$' /usr/dict/words
814     beriberi
815     booboo
816     coco
817     mama
818     murmur
819     papa
820
821 The regexp has a single grouping which considers 4-letter
822 combinations, then 3-letter combinations, I<etc>., and uses C<\g1> to look for
823 a repeat.  Although C<$1> and C<\g1> represent the same thing, care should be
824 taken to use matched variables C<$1>, C<$2>,... only I<outside> a regexp
825 and backreferences C<\g1>, C<\g2>,... only I<inside> a regexp; not doing
826 so may lead to surprising and unsatisfactory results.
827
828
829 =head2 Relative backreferences
830
831 Counting the opening parentheses to get the correct number for a
832 backreference is error-prone as soon as there is more than one
833 capturing group.  A more convenient technique became available
834 with Perl 5.10: relative backreferences. To refer to the immediately
835 preceding capture group one now may write C<\g{-1}>, the next but
836 last is available via C<\g{-2}>, and so on.
837
838 Another good reason in addition to readability and maintainability
839 for using relative backreferences is illustrated by the following example,
840 where a simple pattern for matching peculiar strings is used:
841
842     $a99a = '([a-z])(\d)\g2\g1';   # matches a11a, g22g, x33x, etc.
843
844 Now that we have this pattern stored as a handy string, we might feel
845 tempted to use it as a part of some other pattern:
846
847     $line = "code=e99e";
848     if ($line =~ /^(\w+)=$a99a$/){   # unexpected behavior!
849         print "$1 is valid\n";
850     } else {
851         print "bad line: '$line'\n";
852     }
853
854 But this doesn't match, at least not the way one might expect. Only
855 after inserting the interpolated C<$a99a> and looking at the resulting
856 full text of the regexp is it obvious that the backreferences have
857 backfired. The subexpression C<(\w+)> has snatched number 1 and
858 demoted the groups in C<$a99a> by one rank. This can be avoided by
859 using relative backreferences:
860
861     $a99a = '([a-z])(\d)\g{-1}\g{-2}';  # safe for being interpolated
862
863
864 =head2 Named backreferences
865
866 Perl 5.10 also introduced named capture groups and named backreferences.
867 To attach a name to a capturing group, you write either
868 C<< (?<name>...) >> or C<< (?'name'...) >>.  The backreference may
869 then be written as C<\g{name}>.  It is permissible to attach the
870 same name to more than one group, but then only the leftmost one of the
871 eponymous set can be referenced.  Outside of the pattern a named
872 capture group is accessible through the C<%+> hash.
873
874 Assuming that we have to match calendar dates which may be given in one
875 of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write
876 three suitable patterns where we use C<'d'>, C<'m'> and C<'y'> respectively as the
877 names of the groups capturing the pertaining components of a date. The
878 matching operation combines the three patterns as alternatives:
879
880     $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
881     $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
882     $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
883     for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
884         if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
885             print "day=$+{d} month=$+{m} year=$+{y}\n";
886         }
887     }
888
889 If any of the alternatives matches, the hash C<%+> is bound to contain the
890 three key-value pairs.
891
892
893 =head2 Alternative capture group numbering
894
895 Yet another capturing group numbering technique (also as from Perl 5.10)
896 deals with the problem of referring to groups within a set of alternatives.
897 Consider a pattern for matching a time of the day, civil or military style:
898
899     if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
900         # process hour and minute
901     }
902
903 Processing the results requires an additional if statement to determine
904 whether C<$1> and C<$2> or C<$3> and C<$4> contain the goodies. It would
905 be easier if we could use group numbers 1 and 2 in second alternative as
906 well, and this is exactly what the parenthesized construct C<(?|...)>,
907 set around an alternative achieves. Here is an extended version of the
908 previous pattern:
909
910   if($time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/){
911       print "hour=$1 minute=$2 zone=$3\n";
912   }
913
914 Within the alternative numbering group, group numbers start at the same
915 position for each alternative. After the group, numbering continues
916 with one higher than the maximum reached across all the alternatives.
917
918 =head2 Position information
919
920 In addition to what was matched, Perl also provides the
921 positions of what was matched as contents of the C<@-> and C<@+>
922 arrays. C<$-[0]> is the position of the start of the entire match and
923 C<$+[0]> is the position of the end. Similarly, C<$-[n]> is the
924 position of the start of the C<$n> match and C<$+[n]> is the position
925 of the end. If C<$n> is undefined, so are C<$-[n]> and C<$+[n]>. Then
926 this code
927
928     $x = "Mmm...donut, thought Homer";
929     $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
930     foreach $exp (1..$#-) {
931         no strict 'refs';
932         print "Match $exp: '$$exp' at position ($-[$exp],$+[$exp])\n";
933     }
934
935 prints
936
937     Match 1: 'Mmm' at position (0,3)
938     Match 2: 'donut' at position (6,11)
939
940 Even if there are no groupings in a regexp, it is still possible to
941 find out what exactly matched in a string.  If you use them, Perl
942 will set C<$`> to the part of the string before the match, will set C<$&>
943 to the part of the string that matched, and will set C<$'> to the part
944 of the string after the match.  An example:
945
946     $x = "the cat caught the mouse";
947     $x =~ /cat/;  # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
948     $x =~ /the/;  # $` = '', $& = 'the', $' = ' cat caught the mouse'
949
950 In the second match, C<$`> equals C<''> because the regexp matched at the
951 first character position in the string and stopped; it never saw the
952 second "the".
953
954 If your code is to run on Perl versions earlier than
955 5.20, it is worthwhile to note that using C<$`> and C<$'>
956 slows down regexp matching quite a bit, while C<$&> slows it down to a
957 lesser extent, because if they are used in one regexp in a program,
958 they are generated for I<all> regexps in the program.  So if raw
959 performance is a goal of your application, they should be avoided.
960 If you need to extract the corresponding substrings, use C<@-> and
961 C<@+> instead:
962
963     $` is the same as substr( $x, 0, $-[0] )
964     $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
965     $' is the same as substr( $x, $+[0] )
966
967 As of Perl 5.10, the C<${^PREMATCH}>, C<${^MATCH}> and C<${^POSTMATCH}>
968 variables may be used.  These are only set if the C</p> modifier is
969 present.  Consequently they do not penalize the rest of the program.  In
970 Perl 5.20, C<${^PREMATCH}>, C<${^MATCH}> and C<${^POSTMATCH}> are available
971 whether the C</p> has been used or not (the modifier is ignored), and
972 C<$`>, C<$'> and C<$&> do not cause any speed difference.
973
974 =head2 Non-capturing groupings
975
976 A group that is required to bundle a set of alternatives may or may not be
977 useful as a capturing group.  If it isn't, it just creates a superfluous
978 addition to the set of available capture group values, inside as well as
979 outside the regexp.  Non-capturing groupings, denoted by C<(?:regexp)>,
980 still allow the regexp to be treated as a single unit, but don't establish
981 a capturing group at the same time.  Both capturing and non-capturing
982 groupings are allowed to co-exist in the same regexp.  Because there is
983 no extraction, non-capturing groupings are faster than capturing
984 groupings.  Non-capturing groupings are also handy for choosing exactly
985 which parts of a regexp are to be extracted to matching variables:
986
987     # match a number, $1-$4 are set, but we only want $1
988     /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
989
990     # match a number faster , only $1 is set
991     /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
992
993     # match a number, get $1 = whole number, $2 = exponent
994     /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
995
996 Non-capturing groupings are also useful for removing nuisance
997 elements gathered from a split operation where parentheses are
998 required for some reason:
999
1000     $x = '12aba34ba5';
1001     @num = split /(a|b)+/, $x;    # @num = ('12','a','34','a','5')
1002     @num = split /(?:a|b)+/, $x;  # @num = ('12','34','5')
1003
1004 In Perl 5.22 and later, all groups within a regexp can be set to
1005 non-capturing by using the new C</n> flag:
1006
1007     "hello" =~ /(hi|hello)/n; # $1 is not set!
1008
1009 See L<perlre/"n"> for more information.
1010
1011 =head2 Matching repetitions
1012
1013 The examples in the previous section display an annoying weakness.  We
1014 were only matching 3-letter words, or chunks of words of 4 letters or
1015 less.  We'd like to be able to match words or, more generally, strings
1016 of any length, without writing out tedious alternatives like
1017 C<\w\w\w\w|\w\w\w|\w\w|\w>.
1018
1019 This is exactly the problem the I<quantifier> metacharacters C<'?'>,
1020 C<'*'>, C<'+'>, and C<{}> were created for.  They allow us to delimit the
1021 number of repeats for a portion of a regexp we consider to be a
1022 match.  Quantifiers are put immediately after the character, character
1023 class, or grouping that we want to specify.  They have the following
1024 meanings:
1025
1026 =over 4
1027
1028 =item *
1029
1030 C<a?> means: match C<'a'> 1 or 0 times
1031
1032 =item *
1033
1034 C<a*> means: match C<'a'> 0 or more times, I<i.e.>, any number of times
1035
1036 =item *
1037
1038 C<a+> means: match C<'a'> 1 or more times, I<i.e.>, at least once
1039
1040 =item *
1041
1042 C<a{n,m}> means: match at least C<n> times, but not more than C<m>
1043 times.
1044
1045 =item *
1046
1047 C<a{n,}> means: match at least C<n> or more times
1048
1049 =item *
1050
1051 C<a{n}> means: match exactly C<n> times
1052
1053 =back
1054
1055 Here are some examples:
1056
1057     /[a-z]+\s+\d*/;  # match a lowercase word, at least one space, and
1058                      # any number of digits
1059     /(\w+)\s+\g1/;    # match doubled words of arbitrary length
1060     /y(es)?/i;       # matches 'y', 'Y', or a case-insensitive 'yes'
1061     $year =~ /^\d{2,4}$/;  # make sure year is at least 2 but not more
1062                            # than 4 digits
1063     $year =~ /^\d{4}$|^\d{2}$/; # better match; throw out 3-digit dates
1064     $year =~ /^\d{2}(\d{2})?$/; # same thing written differently.
1065                                 # However, this captures the last two
1066                                 # digits in $1 and the other does not.
1067
1068     % simple_grep '^(\w+)\g1$' /usr/dict/words   # isn't this easier?
1069     beriberi
1070     booboo
1071     coco
1072     mama
1073     murmur
1074     papa
1075
1076 For all of these quantifiers, Perl will try to match as much of the
1077 string as possible, while still allowing the regexp to succeed.  Thus
1078 with C</a?.../>, Perl will first try to match the regexp with the C<'a'>
1079 present; if that fails, Perl will try to match the regexp without the
1080 C<'a'> present.  For the quantifier C<'*'>, we get the following:
1081
1082     $x = "the cat in the hat";
1083     $x =~ /^(.*)(cat)(.*)$/; # matches,
1084                              # $1 = 'the '
1085                              # $2 = 'cat'
1086                              # $3 = ' in the hat'
1087
1088 Which is what we might expect, the match finds the only C<cat> in the
1089 string and locks onto it.  Consider, however, this regexp:
1090
1091     $x =~ /^(.*)(at)(.*)$/; # matches,
1092                             # $1 = 'the cat in the h'
1093                             # $2 = 'at'
1094                             # $3 = ''   (0 characters match)
1095
1096 One might initially guess that Perl would find the C<at> in C<cat> and
1097 stop there, but that wouldn't give the longest possible string to the
1098 first quantifier C<.*>.  Instead, the first quantifier C<.*> grabs as
1099 much of the string as possible while still having the regexp match.  In
1100 this example, that means having the C<at> sequence with the final C<at>
1101 in the string.  The other important principle illustrated here is that,
1102 when there are two or more elements in a regexp, the I<leftmost>
1103 quantifier, if there is one, gets to grab as much of the string as
1104 possible, leaving the rest of the regexp to fight over scraps.  Thus in
1105 our example, the first quantifier C<.*> grabs most of the string, while
1106 the second quantifier C<.*> gets the empty string.   Quantifiers that
1107 grab as much of the string as possible are called I<maximal match> or
1108 I<greedy> quantifiers.
1109
1110 When a regexp can match a string in several different ways, we can use
1111 the principles above to predict which way the regexp will match:
1112
1113 =over 4
1114
1115 =item *
1116
1117 Principle 0: Taken as a whole, any regexp will be matched at the
1118 earliest possible position in the string.
1119
1120 =item *
1121
1122 Principle 1: In an alternation C<a|b|c...>, the leftmost alternative
1123 that allows a match for the whole regexp will be the one used.
1124
1125 =item *
1126
1127 Principle 2: The maximal matching quantifiers C<'?'>, C<'*'>, C<'+'> and
1128 C<{n,m}> will in general match as much of the string as possible while
1129 still allowing the whole regexp to match.
1130
1131 =item *
1132
1133 Principle 3: If there are two or more elements in a regexp, the
1134 leftmost greedy quantifier, if any, will match as much of the string
1135 as possible while still allowing the whole regexp to match.  The next
1136 leftmost greedy quantifier, if any, will try to match as much of the
1137 string remaining available to it as possible, while still allowing the
1138 whole regexp to match.  And so on, until all the regexp elements are
1139 satisfied.
1140
1141 =back
1142
1143 As we have seen above, Principle 0 overrides the others. The regexp
1144 will be matched as early as possible, with the other principles
1145 determining how the regexp matches at that earliest character
1146 position.
1147
1148 Here is an example of these principles in action:
1149
1150     $x = "The programming republic of Perl";
1151     $x =~ /^(.+)(e|r)(.*)$/;  # matches,
1152                               # $1 = 'The programming republic of Pe'
1153                               # $2 = 'r'
1154                               # $3 = 'l'
1155
1156 This regexp matches at the earliest string position, C<'T'>.  One
1157 might think that C<'e'>, being leftmost in the alternation, would be
1158 matched, but C<'r'> produces the longest string in the first quantifier.
1159
1160     $x =~ /(m{1,2})(.*)$/;  # matches,
1161                             # $1 = 'mm'
1162                             # $2 = 'ing republic of Perl'
1163
1164 Here, The earliest possible match is at the first C<'m'> in
1165 C<programming>. C<m{1,2}> is the first quantifier, so it gets to match
1166 a maximal C<mm>.
1167
1168     $x =~ /.*(m{1,2})(.*)$/;  # matches,
1169                               # $1 = 'm'
1170                               # $2 = 'ing republic of Perl'
1171
1172 Here, the regexp matches at the start of the string. The first
1173 quantifier C<.*> grabs as much as possible, leaving just a single
1174 C<'m'> for the second quantifier C<m{1,2}>.
1175
1176     $x =~ /(.?)(m{1,2})(.*)$/;  # matches,
1177                                 # $1 = 'a'
1178                                 # $2 = 'mm'
1179                                 # $3 = 'ing republic of Perl'
1180
1181 Here, C<.?> eats its maximal one character at the earliest possible
1182 position in the string, C<'a'> in C<programming>, leaving C<m{1,2}>
1183 the opportunity to match both C<'m'>'s. Finally,
1184
1185     "aXXXb" =~ /(X*)/; # matches with $1 = ''
1186
1187 because it can match zero copies of C<'X'> at the beginning of the
1188 string.  If you definitely want to match at least one C<'X'>, use
1189 C<X+>, not C<X*>.
1190
1191 Sometimes greed is not good.  At times, we would like quantifiers to
1192 match a I<minimal> piece of string, rather than a maximal piece.  For
1193 this purpose, Larry Wall created the I<minimal match> or
1194 I<non-greedy> quantifiers C<??>, C<*?>, C<+?>, and C<{}?>.  These are
1195 the usual quantifiers with a C<'?'> appended to them.  They have the
1196 following meanings:
1197
1198 =over 4
1199
1200 =item *
1201
1202 C<a??> means: match C<'a'> 0 or 1 times. Try 0 first, then 1.
1203
1204 =item *
1205
1206 C<a*?> means: match C<'a'> 0 or more times, I<i.e.>, any number of times,
1207 but as few times as possible
1208
1209 =item *
1210
1211 C<a+?> means: match C<'a'> 1 or more times, I<i.e.>, at least once, but
1212 as few times as possible
1213
1214 =item *
1215
1216 C<a{n,m}?> means: match at least C<n> times, not more than C<m>
1217 times, as few times as possible
1218
1219 =item *
1220
1221 C<a{n,}?> means: match at least C<n> times, but as few times as
1222 possible
1223
1224 =item *
1225
1226 C<a{n}?> means: match exactly C<n> times.  Because we match exactly
1227 C<n> times, C<a{n}?> is equivalent to C<a{n}> and is just there for
1228 notational consistency.
1229
1230 =back
1231
1232 Let's look at the example above, but with minimal quantifiers:
1233
1234     $x = "The programming republic of Perl";
1235     $x =~ /^(.+?)(e|r)(.*)$/; # matches,
1236                               # $1 = 'Th'
1237                               # $2 = 'e'
1238                               # $3 = ' programming republic of Perl'
1239
1240 The minimal string that will allow both the start of the string C<'^'>
1241 and the alternation to match is C<Th>, with the alternation C<e|r>
1242 matching C<'e'>.  The second quantifier C<.*> is free to gobble up the
1243 rest of the string.
1244
1245     $x =~ /(m{1,2}?)(.*?)$/;  # matches,
1246                               # $1 = 'm'
1247                               # $2 = 'ming republic of Perl'
1248
1249 The first string position that this regexp can match is at the first
1250 C<'m'> in C<programming>. At this position, the minimal C<m{1,2}?>
1251 matches just one C<'m'>.  Although the second quantifier C<.*?> would
1252 prefer to match no characters, it is constrained by the end-of-string
1253 anchor C<'$'> to match the rest of the string.
1254
1255     $x =~ /(.*?)(m{1,2}?)(.*)$/;  # matches,
1256                                   # $1 = 'The progra'
1257                                   # $2 = 'm'
1258                                   # $3 = 'ming republic of Perl'
1259
1260 In this regexp, you might expect the first minimal quantifier C<.*?>
1261 to match the empty string, because it is not constrained by a C<'^'>
1262 anchor to match the beginning of the word.  Principle 0 applies here,
1263 however.  Because it is possible for the whole regexp to match at the
1264 start of the string, it I<will> match at the start of the string.  Thus
1265 the first quantifier has to match everything up to the first C<'m'>.  The
1266 second minimal quantifier matches just one C<'m'> and the third
1267 quantifier matches the rest of the string.
1268
1269     $x =~ /(.??)(m{1,2})(.*)$/;  # matches,
1270                                  # $1 = 'a'
1271                                  # $2 = 'mm'
1272                                  # $3 = 'ing republic of Perl'
1273
1274 Just as in the previous regexp, the first quantifier C<.??> can match
1275 earliest at position C<'a'>, so it does.  The second quantifier is
1276 greedy, so it matches C<mm>, and the third matches the rest of the
1277 string.
1278
1279 We can modify principle 3 above to take into account non-greedy
1280 quantifiers:
1281
1282 =over 4
1283
1284 =item *
1285
1286 Principle 3: If there are two or more elements in a regexp, the
1287 leftmost greedy (non-greedy) quantifier, if any, will match as much
1288 (little) of the string as possible while still allowing the whole
1289 regexp to match.  The next leftmost greedy (non-greedy) quantifier, if
1290 any, will try to match as much (little) of the string remaining
1291 available to it as possible, while still allowing the whole regexp to
1292 match.  And so on, until all the regexp elements are satisfied.
1293
1294 =back
1295
1296 Just like alternation, quantifiers are also susceptible to
1297 backtracking.  Here is a step-by-step analysis of the example
1298
1299     $x = "the cat in the hat";
1300     $x =~ /^(.*)(at)(.*)$/; # matches,
1301                             # $1 = 'the cat in the h'
1302                             # $2 = 'at'
1303                             # $3 = ''   (0 matches)
1304
1305 =over 4
1306
1307 =item Z<>0.  Start with the first letter in the string C<'t'>.
1308
1309 E<nbsp>
1310
1311 =item Z<>1.  The first quantifier C<'.*'> starts out by matching the whole
1312 string "C<the cat in the hat>".
1313
1314 E<nbsp>
1315
1316 =item Z<>2.  C<'a'> in the regexp element C<'at'> doesn't match the end
1317 of the string.  Backtrack one character.
1318
1319 E<nbsp>
1320
1321 =item Z<>3.  C<'a'> in the regexp element C<'at'> still doesn't match
1322 the last letter of the string C<'t'>, so backtrack one more character.
1323
1324 E<nbsp>
1325
1326 =item Z<>4.  Now we can match the C<'a'> and the C<'t'>.
1327
1328 E<nbsp>
1329
1330 =item Z<>5.  Move on to the third element C<'.*'>.  Since we are at the
1331 end of the string and C<'.*'> can match 0 times, assign it the empty
1332 string.
1333
1334 E<nbsp>
1335
1336 =item Z<>6.  We are done!
1337
1338 =back
1339
1340 Most of the time, all this moving forward and backtracking happens
1341 quickly and searching is fast. There are some pathological regexps,
1342 however, whose execution time exponentially grows with the size of the
1343 string.  A typical structure that blows up in your face is of the form
1344
1345     /(a|b+)*/;
1346
1347 The problem is the nested indeterminate quantifiers.  There are many
1348 different ways of partitioning a string of length n between the C<'+'>
1349 and C<'*'>: one repetition with C<b+> of length n, two repetitions with
1350 the first C<b+> length k and the second with length n-k, m repetitions
1351 whose bits add up to length n, I<etc>.  In fact there are an exponential
1352 number of ways to partition a string as a function of its length.  A
1353 regexp may get lucky and match early in the process, but if there is
1354 no match, Perl will try I<every> possibility before giving up.  So be
1355 careful with nested C<'*'>'s, C<{n,m}>'s, and C<'+'>'s.  The book
1356 I<Mastering Regular Expressions> by Jeffrey Friedl gives a wonderful
1357 discussion of this and other efficiency issues.
1358
1359
1360 =head2 Possessive quantifiers
1361
1362 Backtracking during the relentless search for a match may be a waste
1363 of time, particularly when the match is bound to fail.  Consider
1364 the simple pattern
1365
1366     /^\w+\s+\w+$/; # a word, spaces, a word
1367
1368 Whenever this is applied to a string which doesn't quite meet the
1369 pattern's expectations such as S<C<"abc  ">> or S<C<"abc  def ">>,
1370 the regexp engine will backtrack, approximately once for each character
1371 in the string.  But we know that there is no way around taking I<all>
1372 of the initial word characters to match the first repetition, that I<all>
1373 spaces must be eaten by the middle part, and the same goes for the second
1374 word.
1375
1376 With the introduction of the I<possessive quantifiers> in Perl 5.10, we
1377 have a way of instructing the regexp engine not to backtrack, with the
1378 usual quantifiers with a C<'+'> appended to them.  This makes them greedy as
1379 well as stingy; once they succeed they won't give anything back to permit
1380 another solution. They have the following meanings:
1381
1382 =over 4
1383
1384 =item *
1385
1386 C<a{n,m}+> means: match at least C<n> times, not more than C<m> times,
1387 as many times as possible, and don't give anything up. C<a?+> is short
1388 for C<a{0,1}+>
1389
1390 =item *
1391
1392 C<a{n,}+> means: match at least C<n> times, but as many times as possible,
1393 and don't give anything up. C<a*+> is short for C<a{0,}+> and C<a++> is
1394 short for C<a{1,}+>.
1395
1396 =item *
1397
1398 C<a{n}+> means: match exactly C<n> times.  It is just there for
1399 notational consistency.
1400
1401 =back
1402
1403 These possessive quantifiers represent a special case of a more general
1404 concept, the I<independent subexpression>, see below.
1405
1406 As an example where a possessive quantifier is suitable we consider
1407 matching a quoted string, as it appears in several programming languages.
1408 The backslash is used as an escape character that indicates that the
1409 next character is to be taken literally, as another character for the
1410 string.  Therefore, after the opening quote, we expect a (possibly
1411 empty) sequence of alternatives: either some character except an
1412 unescaped quote or backslash or an escaped character.
1413
1414     /"(?:[^"\\]++|\\.)*+"/;
1415
1416
1417 =head2 Building a regexp
1418
1419 At this point, we have all the basic regexp concepts covered, so let's
1420 give a more involved example of a regular expression.  We will build a
1421 regexp that matches numbers.
1422
1423 The first task in building a regexp is to decide what we want to match
1424 and what we want to exclude.  In our case, we want to match both
1425 integers and floating point numbers and we want to reject any string
1426 that isn't a number.
1427
1428 The next task is to break the problem down into smaller problems that
1429 are easily converted into a regexp.
1430
1431 The simplest case is integers.  These consist of a sequence of digits,
1432 with an optional sign in front.  The digits we can represent with
1433 C<\d+> and the sign can be matched with C<[+-]>.  Thus the integer
1434 regexp is
1435
1436     /[+-]?\d+/;  # matches integers
1437
1438 A floating point number potentially has a sign, an integral part, a
1439 decimal point, a fractional part, and an exponent.  One or more of these
1440 parts is optional, so we need to check out the different
1441 possibilities.  Floating point numbers which are in proper form include
1442 123., 0.345, .34, -1e6, and 25.4E-72.  As with integers, the sign out
1443 front is completely optional and can be matched by C<[+-]?>.  We can
1444 see that if there is no exponent, floating point numbers must have a
1445 decimal point, otherwise they are integers.  We might be tempted to
1446 model these with C<\d*\.\d*>, but this would also match just a single
1447 decimal point, which is not a number.  So the three cases of floating
1448 point number without exponent are
1449
1450    /[+-]?\d+\./;  # 1., 321., etc.
1451    /[+-]?\.\d+/;  # .1, .234, etc.
1452    /[+-]?\d+\.\d+/;  # 1.0, 30.56, etc.
1453
1454 These can be combined into a single regexp with a three-way alternation:
1455
1456    /[+-]?(\d+\.\d+|\d+\.|\.\d+)/;  # floating point, no exponent
1457
1458 In this alternation, it is important to put C<'\d+\.\d+'> before
1459 C<'\d+\.'>.  If C<'\d+\.'> were first, the regexp would happily match that
1460 and ignore the fractional part of the number.
1461
1462 Now consider floating point numbers with exponents.  The key
1463 observation here is that I<both> integers and numbers with decimal
1464 points are allowed in front of an exponent.  Then exponents, like the
1465 overall sign, are independent of whether we are matching numbers with
1466 or without decimal points, and can be "decoupled" from the
1467 mantissa.  The overall form of the regexp now becomes clear:
1468
1469     /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
1470
1471 The exponent is an C<'e'> or C<'E'>, followed by an integer.  So the
1472 exponent regexp is
1473
1474    /[eE][+-]?\d+/;  # exponent
1475
1476 Putting all the parts together, we get a regexp that matches numbers:
1477
1478    /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/;  # Ta da!
1479
1480 Long regexps like this may impress your friends, but can be hard to
1481 decipher.  In complex situations like this, the C</x> modifier for a
1482 match is invaluable.  It allows one to put nearly arbitrary whitespace
1483 and comments into a regexp without affecting their meaning.  Using it,
1484 we can rewrite our "extended" regexp in the more pleasing form
1485
1486    /^
1487       [+-]?         # first, match an optional sign
1488       (             # then match integers or f.p. mantissas:
1489           \d+\.\d+  # mantissa of the form a.b
1490          |\d+\.     # mantissa of the form a.
1491          |\.\d+     # mantissa of the form .b
1492          |\d+       # integer of the form a
1493       )
1494       ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
1495    $/x;
1496
1497 If whitespace is mostly irrelevant, how does one include space
1498 characters in an extended regexp? The answer is to backslash it
1499 S<C<'\ '>> or put it in a character class S<C<[ ]>>.  The same thing
1500 goes for pound signs: use C<\#> or C<[#]>.  For instance, Perl allows
1501 a space between the sign and the mantissa or integer, and we could add
1502 this to our regexp as follows:
1503
1504    /^
1505       [+-]?\ *      # first, match an optional sign *and space*
1506       (             # then match integers or f.p. mantissas:
1507           \d+\.\d+  # mantissa of the form a.b
1508          |\d+\.     # mantissa of the form a.
1509          |\.\d+     # mantissa of the form .b
1510          |\d+       # integer of the form a
1511       )
1512       ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
1513    $/x;
1514
1515 In this form, it is easier to see a way to simplify the
1516 alternation.  Alternatives 1, 2, and 4 all start with C<\d+>, so it
1517 could be factored out:
1518
1519    /^
1520       [+-]?\ *      # first, match an optional sign
1521       (             # then match integers or f.p. mantissas:
1522           \d+       # start out with a ...
1523           (
1524               \.\d* # mantissa of the form a.b or a.
1525           )?        # ? takes care of integers of the form a
1526          |\.\d+     # mantissa of the form .b
1527       )
1528       ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
1529    $/x;
1530
1531 Starting in Perl v5.26, specifying C</xx> changes the square-bracketed
1532 portions of a pattern to ignore tabs and space characters unless they
1533 are escaped by preceding them with a backslash.  So, we could write
1534
1535    /^
1536       [ + - ]?\ *   # first, match an optional sign
1537       (             # then match integers or f.p. mantissas:
1538           \d+       # start out with a ...
1539           (
1540               \.\d* # mantissa of the form a.b or a.
1541           )?        # ? takes care of integers of the form a
1542          |\.\d+     # mantissa of the form .b
1543       )
1544       ( [ e E ] [ + - ]? \d+ )?  # finally, optionally match an exponent
1545    $/xx;
1546
1547 This doesn't really improve the legibility of this example, but it's
1548 available in case you want it.  Squashing the pattern down to the
1549 compact form, we have
1550
1551     /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
1552
1553 This is our final regexp.  To recap, we built a regexp by
1554
1555 =over 4
1556
1557 =item *
1558
1559 specifying the task in detail,
1560
1561 =item *
1562
1563 breaking down the problem into smaller parts,
1564
1565 =item *
1566
1567 translating the small parts into regexps,
1568
1569 =item *
1570
1571 combining the regexps,
1572
1573 =item *
1574
1575 and optimizing the final combined regexp.
1576
1577 =back
1578
1579 These are also the typical steps involved in writing a computer
1580 program.  This makes perfect sense, because regular expressions are
1581 essentially programs written in a little computer language that specifies
1582 patterns.
1583
1584 =head2 Using regular expressions in Perl
1585
1586 The last topic of Part 1 briefly covers how regexps are used in Perl
1587 programs.  Where do they fit into Perl syntax?
1588
1589 We have already introduced the matching operator in its default
1590 C</regexp/> and arbitrary delimiter C<m!regexp!> forms.  We have used
1591 the binding operator C<=~> and its negation C<!~> to test for string
1592 matches.  Associated with the matching operator, we have discussed the
1593 single line C</s>, multi-line C</m>, case-insensitive C</i> and
1594 extended C</x> modifiers.  There are a few more things you might
1595 want to know about matching operators.
1596
1597 =head3 Prohibiting substitution
1598
1599 If you change C<$pattern> after the first substitution happens, Perl
1600 will ignore it.  If you don't want any substitutions at all, use the
1601 special delimiter C<m''>:
1602
1603     @pattern = ('Seuss');
1604     while (<>) {
1605         print if m'@pattern';  # matches literal '@pattern', not 'Seuss'
1606     }
1607
1608 Similar to strings, C<m''> acts like apostrophes on a regexp; all other
1609 C<'m'> delimiters act like quotes.  If the regexp evaluates to the empty string,
1610 the regexp in the I<last successful match> is used instead.  So we have
1611
1612     "dog" =~ /d/;  # 'd' matches
1613     "dogbert" =~ //;  # this matches the 'd' regexp used before
1614
1615
1616 =head3 Global matching
1617
1618 The final two modifiers we will discuss here,
1619 C</g> and C</c>, concern multiple matches.
1620 The modifier C</g> stands for global matching and allows the
1621 matching operator to match within a string as many times as possible.
1622 In scalar context, successive invocations against a string will have
1623 C</g> jump from match to match, keeping track of position in the
1624 string as it goes along.  You can get or set the position with the
1625 C<pos()> function.
1626
1627 The use of C</g> is shown in the following example.  Suppose we have
1628 a string that consists of words separated by spaces.  If we know how
1629 many words there are in advance, we could extract the words using
1630 groupings:
1631
1632     $x = "cat dog house"; # 3 words
1633     $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
1634                                            # $1 = 'cat'
1635                                            # $2 = 'dog'
1636                                            # $3 = 'house'
1637
1638 But what if we had an indeterminate number of words? This is the sort
1639 of task C</g> was made for.  To extract all words, form the simple
1640 regexp C<(\w+)> and loop over all matches with C</(\w+)/g>:
1641
1642     while ($x =~ /(\w+)/g) {
1643         print "Word is $1, ends at position ", pos $x, "\n";
1644     }
1645
1646 prints
1647
1648     Word is cat, ends at position 3
1649     Word is dog, ends at position 7
1650     Word is house, ends at position 13
1651
1652 A failed match or changing the target string resets the position.  If
1653 you don't want the position reset after failure to match, add the
1654 C</c>, as in C</regexp/gc>.  The current position in the string is
1655 associated with the string, not the regexp.  This means that different
1656 strings have different positions and their respective positions can be
1657 set or read independently.
1658
1659 In list context, C</g> returns a list of matched groupings, or if
1660 there are no groupings, a list of matches to the whole regexp.  So if
1661 we wanted just the words, we could use
1662
1663     @words = ($x =~ /(\w+)/g);  # matches,
1664                                 # $words[0] = 'cat'
1665                                 # $words[1] = 'dog'
1666                                 # $words[2] = 'house'
1667
1668 Closely associated with the C</g> modifier is the C<\G> anchor.  The
1669 C<\G> anchor matches at the point where the previous C</g> match left
1670 off.  C<\G> allows us to easily do context-sensitive matching:
1671
1672     $metric = 1;  # use metric units
1673     ...
1674     $x = <FILE>;  # read in measurement
1675     $x =~ /^([+-]?\d+)\s*/g;  # get magnitude
1676     $weight = $1;
1677     if ($metric) { # error checking
1678         print "Units error!" unless $x =~ /\Gkg\./g;
1679     }
1680     else {
1681         print "Units error!" unless $x =~ /\Glbs\./g;
1682     }
1683     $x =~ /\G\s+(widget|sprocket)/g;  # continue processing
1684
1685 The combination of C</g> and C<\G> allows us to process the string a
1686 bit at a time and use arbitrary Perl logic to decide what to do next.
1687 Currently, the C<\G> anchor is only fully supported when used to anchor
1688 to the start of the pattern.
1689
1690 C<\G> is also invaluable in processing fixed-length records with
1691 regexps.  Suppose we have a snippet of coding region DNA, encoded as
1692 base pair letters C<ATCGTTGAAT...> and we want to find all the stop
1693 codons C<TGA>.  In a coding region, codons are 3-letter sequences, so
1694 we can think of the DNA snippet as a sequence of 3-letter records.  The
1695 naive regexp
1696
1697     # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
1698     $dna = "ATCGTTGAATGCAAATGACATGAC";
1699     $dna =~ /TGA/;
1700
1701 doesn't work; it may match a C<TGA>, but there is no guarantee that
1702 the match is aligned with codon boundaries, I<e.g.>, the substring
1703 S<C<GTT GAA>> gives a match.  A better solution is
1704
1705     while ($dna =~ /(\w\w\w)*?TGA/g) {  # note the minimal *?
1706         print "Got a TGA stop codon at position ", pos $dna, "\n";
1707     }
1708
1709 which prints
1710
1711     Got a TGA stop codon at position 18
1712     Got a TGA stop codon at position 23
1713
1714 Position 18 is good, but position 23 is bogus.  What happened?
1715
1716 The answer is that our regexp works well until we get past the last
1717 real match.  Then the regexp will fail to match a synchronized C<TGA>
1718 and start stepping ahead one character position at a time, not what we
1719 want.  The solution is to use C<\G> to anchor the match to the codon
1720 alignment:
1721
1722     while ($dna =~ /\G(\w\w\w)*?TGA/g) {
1723         print "Got a TGA stop codon at position ", pos $dna, "\n";
1724     }
1725
1726 This prints
1727
1728     Got a TGA stop codon at position 18
1729
1730 which is the correct answer.  This example illustrates that it is
1731 important not only to match what is desired, but to reject what is not
1732 desired.
1733
1734 (There are other regexp modifiers that are available, such as
1735 C</o>, but their specialized uses are beyond the
1736 scope of this introduction.  )
1737
1738 =head3 Search and replace
1739
1740 Regular expressions also play a big role in I<search and replace>
1741 operations in Perl.  Search and replace is accomplished with the
1742 C<s///> operator.  The general form is
1743 C<s/regexp/replacement/modifiers>, with everything we know about
1744 regexps and modifiers applying in this case as well.  The
1745 I<replacement> is a Perl double-quoted string that replaces in the
1746 string whatever is matched with the C<regexp>.  The operator C<=~> is
1747 also used here to associate a string with C<s///>.  If matching
1748 against C<$_>, the S<C<$_ =~>> can be dropped.  If there is a match,
1749 C<s///> returns the number of substitutions made; otherwise it returns
1750 false.  Here are a few examples:
1751
1752     $x = "Time to feed the cat!";
1753     $x =~ s/cat/hacker/;   # $x contains "Time to feed the hacker!"
1754     if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
1755         $more_insistent = 1;
1756     }
1757     $y = "'quoted words'";
1758     $y =~ s/^'(.*)'$/$1/;  # strip single quotes,
1759                            # $y contains "quoted words"
1760
1761 In the last example, the whole string was matched, but only the part
1762 inside the single quotes was grouped.  With the C<s///> operator, the
1763 matched variables C<$1>, C<$2>, I<etc>. are immediately available for use
1764 in the replacement expression, so we use C<$1> to replace the quoted
1765 string with just what was quoted.  With the global modifier, C<s///g>
1766 will search and replace all occurrences of the regexp in the string:
1767
1768     $x = "I batted 4 for 4";
1769     $x =~ s/4/four/;   # doesn't do it all:
1770                        # $x contains "I batted four for 4"
1771     $x = "I batted 4 for 4";
1772     $x =~ s/4/four/g;  # does it all:
1773                        # $x contains "I batted four for four"
1774
1775 If you prefer "regex" over "regexp" in this tutorial, you could use
1776 the following program to replace it:
1777
1778     % cat > simple_replace
1779     #!/usr/bin/perl
1780     $regexp = shift;
1781     $replacement = shift;
1782     while (<>) {
1783         s/$regexp/$replacement/g;
1784         print;
1785     }
1786     ^D
1787
1788     % simple_replace regexp regex perlretut.pod
1789
1790 In C<simple_replace> we used the C<s///g> modifier to replace all
1791 occurrences of the regexp on each line.  (Even though the regular
1792 expression appears in a loop, Perl is smart enough to compile it
1793 only once.)  As with C<simple_grep>, both the
1794 C<print> and the C<s/$regexp/$replacement/g> use C<$_> implicitly.
1795
1796 If you don't want C<s///> to change your original variable you can use
1797 the non-destructive substitute modifier, C<s///r>.  This changes the
1798 behavior so that C<s///r> returns the final substituted string
1799 (instead of the number of substitutions):
1800
1801     $x = "I like dogs.";
1802     $y = $x =~ s/dogs/cats/r;
1803     print "$x $y\n";
1804
1805 That example will print "I like dogs. I like cats". Notice the original
1806 C<$x> variable has not been affected. The overall
1807 result of the substitution is instead stored in C<$y>. If the
1808 substitution doesn't affect anything then the original string is
1809 returned:
1810
1811     $x = "I like dogs.";
1812     $y = $x =~ s/elephants/cougars/r;
1813     print "$x $y\n"; # prints "I like dogs. I like dogs."
1814
1815 One other interesting thing that the C<s///r> flag allows is chaining
1816 substitutions:
1817
1818     $x = "Cats are great.";
1819     print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
1820         s/Frogs/Hedgehogs/r, "\n";
1821     # prints "Hedgehogs are great."
1822
1823 A modifier available specifically to search and replace is the
1824 C<s///e> evaluation modifier.  C<s///e> treats the
1825 replacement text as Perl code, rather than a double-quoted
1826 string.  The value that the code returns is substituted for the
1827 matched substring.  C<s///e> is useful if you need to do a bit of
1828 computation in the process of replacing text.  This example counts
1829 character frequencies in a line:
1830
1831     $x = "Bill the cat";
1832     $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
1833     print "frequency of '$_' is $chars{$_}\n"
1834         foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
1835
1836 This prints
1837
1838     frequency of ' ' is 2
1839     frequency of 't' is 2
1840     frequency of 'l' is 2
1841     frequency of 'B' is 1
1842     frequency of 'c' is 1
1843     frequency of 'e' is 1
1844     frequency of 'h' is 1
1845     frequency of 'i' is 1
1846     frequency of 'a' is 1
1847
1848 As with the match C<m//> operator, C<s///> can use other delimiters,
1849 such as C<s!!!> and C<s{}{}>, and even C<s{}//>.  If single quotes are
1850 used C<s'''>, then the regexp and replacement are
1851 treated as single-quoted strings and there are no
1852 variable substitutions.  C<s///> in list context
1853 returns the same thing as in scalar context, I<i.e.>, the number of
1854 matches.
1855
1856 =head3 The split function
1857
1858 The C<split()> function is another place where a regexp is used.
1859 C<split /regexp/, string, limit> separates the C<string> operand into
1860 a list of substrings and returns that list.  The regexp must be designed
1861 to match whatever constitutes the separators for the desired substrings.
1862 The C<limit>, if present, constrains splitting into no more than C<limit>
1863 number of strings.  For example, to split a string into words, use
1864
1865     $x = "Calvin and Hobbes";
1866     @words = split /\s+/, $x;  # $word[0] = 'Calvin'
1867                                # $word[1] = 'and'
1868                                # $word[2] = 'Hobbes'
1869
1870 If the empty regexp C<//> is used, the regexp always matches and
1871 the string is split into individual characters.  If the regexp has
1872 groupings, then the resulting list contains the matched substrings from the
1873 groupings as well.  For instance,
1874
1875     $x = "/usr/bin/perl";
1876     @dirs = split m!/!, $x;  # $dirs[0] = ''
1877                              # $dirs[1] = 'usr'
1878                              # $dirs[2] = 'bin'
1879                              # $dirs[3] = 'perl'
1880     @parts = split m!(/)!, $x;  # $parts[0] = ''
1881                                 # $parts[1] = '/'
1882                                 # $parts[2] = 'usr'
1883                                 # $parts[3] = '/'
1884                                 # $parts[4] = 'bin'
1885                                 # $parts[5] = '/'
1886                                 # $parts[6] = 'perl'
1887
1888 Since the first character of C<$x> matched the regexp, C<split> prepended
1889 an empty initial element to the list.
1890
1891 If you have read this far, congratulations! You now have all the basic
1892 tools needed to use regular expressions to solve a wide range of text
1893 processing problems.  If this is your first time through the tutorial,
1894 why not stop here and play around with regexps a while....  S<Part 2>
1895 concerns the more esoteric aspects of regular expressions and those
1896 concepts certainly aren't needed right at the start.
1897
1898 =head1 Part 2: Power tools
1899
1900 OK, you know the basics of regexps and you want to know more.  If
1901 matching regular expressions is analogous to a walk in the woods, then
1902 the tools discussed in Part 1 are analogous to topo maps and a
1903 compass, basic tools we use all the time.  Most of the tools in part 2
1904 are analogous to flare guns and satellite phones.  They aren't used
1905 too often on a hike, but when we are stuck, they can be invaluable.
1906
1907 What follows are the more advanced, less used, or sometimes esoteric
1908 capabilities of Perl regexps.  In Part 2, we will assume you are
1909 comfortable with the basics and concentrate on the advanced features.
1910
1911 =head2 More on characters, strings, and character classes
1912
1913 There are a number of escape sequences and character classes that we
1914 haven't covered yet.
1915
1916 There are several escape sequences that convert characters or strings
1917 between upper and lower case, and they are also available within
1918 patterns.  C<\l> and C<\u> convert the next character to lower or
1919 upper case, respectively:
1920
1921     $x = "perl";
1922     $string =~ /\u$x/;  # matches 'Perl' in $string
1923     $x = "M(rs?|s)\\."; # note the double backslash
1924     $string =~ /\l$x/;  # matches 'mr.', 'mrs.', and 'ms.',
1925
1926 A C<\L> or C<\U> indicates a lasting conversion of case, until
1927 terminated by C<\E> or thrown over by another C<\U> or C<\L>:
1928
1929     $x = "This word is in lower case:\L SHOUT\E";
1930     $x =~ /shout/;       # matches
1931     $x = "I STILL KEYPUNCH CARDS FOR MY 360";
1932     $x =~ /\Ukeypunch/;  # matches punch card string
1933
1934 If there is no C<\E>, case is converted until the end of the
1935 string. The regexps C<\L\u$word> or C<\u\L$word> convert the first
1936 character of C<$word> to uppercase and the rest of the characters to
1937 lowercase.
1938
1939 Control characters can be escaped with C<\c>, so that a control-Z
1940 character would be matched with C<\cZ>.  The escape sequence
1941 C<\Q>...C<\E> quotes, or protects most non-alphabetic characters.   For
1942 instance,
1943
1944     $x = "\QThat !^*&%~& cat!";
1945     $x =~ /\Q!^*&%~&\E/;  # check for rough language
1946
1947 It does not protect C<'$'> or C<'@'>, so that variables can still be
1948 substituted.
1949
1950 C<\Q>, C<\L>, C<\l>, C<\U>, C<\u> and C<\E> are actually part of
1951 double-quotish syntax, and not part of regexp syntax proper.  They will
1952 work if they appear in a regular expression embedded directly in a
1953 program, but not when contained in a string that is interpolated in a
1954 pattern.
1955
1956 Perl regexps can handle more than just the
1957 standard ASCII character set.  Perl supports I<Unicode>, a standard
1958 for representing the alphabets from virtually all of the world's written
1959 languages, and a host of symbols.  Perl's text strings are Unicode strings, so
1960 they can contain characters with a value (codepoint or character number) higher
1961 than 255.
1962
1963 What does this mean for regexps? Well, regexp users don't need to know
1964 much about Perl's internal representation of strings.  But they do need
1965 to know 1) how to represent Unicode characters in a regexp and 2) that
1966 a matching operation will treat the string to be searched as a sequence
1967 of characters, not bytes.  The answer to 1) is that Unicode characters
1968 greater than C<chr(255)> are represented using the C<\x{hex}> notation, because
1969 C<\x>I<XY> (without curly braces and I<XY> are two hex digits) doesn't
1970 go further than 255.  (Starting in Perl 5.14, if you're an octal fan,
1971 you can also use C<\o{oct}>.)
1972
1973     /\x{263a}/;  # match a Unicode smiley face :)
1974
1975 B<NOTE>: In Perl 5.6.0 it used to be that one needed to say C<use
1976 utf8> to use any Unicode features.  This is no more the case: for
1977 almost all Unicode processing, the explicit C<utf8> pragma is not
1978 needed.  (The only case where it matters is if your Perl script is in
1979 Unicode and encoded in UTF-8, then an explicit C<use utf8> is needed.)
1980
1981 Figuring out the hexadecimal sequence of a Unicode character you want
1982 or deciphering someone else's hexadecimal Unicode regexp is about as
1983 much fun as programming in machine code.  So another way to specify
1984 Unicode characters is to use the I<named character> escape
1985 sequence C<\N{I<name>}>.  I<name> is a name for the Unicode character, as
1986 specified in the Unicode standard.  For instance, if we wanted to
1987 represent or match the astrological sign for the planet Mercury, we
1988 could use
1989
1990     $x = "abc\N{MERCURY}def";
1991     $x =~ /\N{MERCURY}/;   # matches
1992
1993 One can also use "short" names:
1994
1995     print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
1996     print "\N{greek:Sigma} is an upper-case sigma.\n";
1997
1998 You can also restrict names to a certain alphabet by specifying the
1999 L<charnames> pragma:
2000
2001     use charnames qw(greek);
2002     print "\N{sigma} is Greek sigma\n";
2003
2004 An index of character names is available on-line from the Unicode
2005 Consortium, L<https://www.unicode.org/charts/charindex.html>; explanatory
2006 material with links to other resources at
2007 L<https://www.unicode.org/standard/where>.
2008
2009 Starting in Perl v5.32, an alternative to C<\N{...}> for full names is
2010 available, and that is to say
2011
2012  /\p{Name=greek small letter sigma}/
2013
2014 The casing of the character name is irrelevant when used in C<\p{}>, as
2015 are most spaces, underscores and hyphens.  (A few outlier characters
2016 cause problems with ignoring all of them always.  The details (which you
2017 can look up when you get more proficient, and if ever needed) are in
2018 L<https://www.unicode.org/reports/tr44/tr44-24.html#UAX44-LM2>).
2019
2020 The answer to requirement 2) is that a regexp (mostly)
2021 uses Unicode characters.  The "mostly" is for messy backward
2022 compatibility reasons, but starting in Perl 5.14, any regexp compiled in
2023 the scope of a C<use feature 'unicode_strings'> (which is automatically
2024 turned on within the scope of a C<use 5.012> or higher) will turn that
2025 "mostly" into "always".  If you want to handle Unicode properly, you
2026 should ensure that C<'unicode_strings'> is turned on.
2027 Internally, this is encoded to bytes using either UTF-8 or a native 8
2028 bit encoding, depending on the history of the string, but conceptually
2029 it is a sequence of characters, not bytes. See L<perlunitut> for a
2030 tutorial about that.
2031
2032 Let us now discuss Unicode character classes, most usually called
2033 "character properties".  These are represented by the C<\p{I<name>}>
2034 escape sequence.  The negation of this is C<\P{I<name>}>.  For example,
2035 to match lower and uppercase characters,
2036
2037     $x = "BOB";
2038     $x =~ /^\p{IsUpper}/;   # matches, uppercase char class
2039     $x =~ /^\P{IsUpper}/;   # doesn't match, char class sans uppercase
2040     $x =~ /^\p{IsLower}/;   # doesn't match, lowercase char class
2041     $x =~ /^\P{IsLower}/;   # matches, char class sans lowercase
2042
2043 (The "C<Is>" is optional.)
2044
2045 There are many, many Unicode character properties.  For the full list
2046 see L<perluniprops>.  Most of them have synonyms with shorter names,
2047 also listed there.  Some synonyms are a single character.  For these,
2048 you can drop the braces.  For instance, C<\pM> is the same thing as
2049 C<\p{Mark}>, meaning things like accent marks.
2050
2051 The Unicode C<\p{Script}> and C<\p{Script_Extensions}> properties are
2052 used to categorize every Unicode character into the language script it
2053 is written in.  (C<Script_Extensions> is an improved version of
2054 C<Script>, which is retained for backward compatibility, and so you
2055 should generally use C<Script_Extensions>.)
2056 For example,
2057 English, French, and a bunch of other European languages are written in
2058 the Latin script.  But there is also the Greek script, the Thai script,
2059 the Katakana script, I<etc>.  You can test whether a character is in a
2060 particular script (based on C<Script_Extensions>) with, for example
2061 C<\p{Latin}>, C<\p{Greek}>, or C<\p{Katakana}>.  To test if it isn't in
2062 the Balinese script, you would use C<\P{Balinese}>.
2063
2064 What we have described so far is the single form of the C<\p{...}> character
2065 classes.  There is also a compound form which you may run into.  These
2066 look like C<\p{I<name>=I<value>}> or C<\p{I<name>:I<value>}> (the equals sign and colon
2067 can be used interchangeably).  These are more general than the single form,
2068 and in fact most of the single forms are just Perl-defined shortcuts for common
2069 compound forms.  For example, the script examples in the previous paragraph
2070 could be written equivalently as C<\p{Script_Extensions=Latin}>, C<\p{Script_Extensions:Greek}>,
2071 C<\p{script_extensions=katakana}>, and C<\P{script_extensions=balinese}> (case is irrelevant
2072 between the C<{}> braces).  You may
2073 never have to use the compound forms, but sometimes it is necessary, and their
2074 use can make your code easier to understand.
2075
2076 C<\X> is an abbreviation for a character class that comprises
2077 a Unicode I<extended grapheme cluster>.  This represents a "logical character":
2078 what appears to be a single character, but may be represented internally by more
2079 than one.  As an example, using the Unicode full names, I<e.g.>, "S<A + COMBINING
2080 RING>" is a grapheme cluster with base character "A" and combining character
2081 "S<COMBINING RING>, which translates in Danish to "A" with the circle atop it,
2082 as in the word E<Aring>ngstrom.
2083
2084 For the full and latest information about Unicode see the latest
2085 Unicode standard, or the Unicode Consortium's website L<https://www.unicode.org>
2086
2087 As if all those classes weren't enough, Perl also defines POSIX-style
2088 character classes.  These have the form C<[:I<name>:]>, with I<name> the
2089 name of the POSIX class.  The POSIX classes are C<alpha>, C<alnum>,
2090 C<ascii>, C<cntrl>, C<digit>, C<graph>, C<lower>, C<print>, C<punct>,
2091 C<space>, C<upper>, and C<xdigit>, and two extensions, C<word> (a Perl
2092 extension to match C<\w>), and C<blank> (a GNU extension).  The C</a>
2093 modifier restricts these to matching just in the ASCII range; otherwise
2094 they can match the same as their corresponding Perl Unicode classes:
2095 C<[:upper:]> is the same as C<\p{IsUpper}>, I<etc>.  (There are some
2096 exceptions and gotchas with this; see L<perlrecharclass> for a full
2097 discussion.) The C<[:digit:]>, C<[:word:]>, and
2098 C<[:space:]> correspond to the familiar C<\d>, C<\w>, and C<\s>
2099 character classes.  To negate a POSIX class, put a C<'^'> in front of
2100 the name, so that, I<e.g.>, C<[:^digit:]> corresponds to C<\D> and, under
2101 Unicode, C<\P{IsDigit}>.  The Unicode and POSIX character classes can
2102 be used just like C<\d>, with the exception that POSIX character
2103 classes can only be used inside of a character class:
2104
2105     /\s+[abc[:digit:]xyz]\s*/;  # match a,b,c,x,y,z, or a digit
2106     /^=item\s[[:digit:]]/;      # match '=item',
2107                                 # followed by a space and a digit
2108     /\s+[abc\p{IsDigit}xyz]\s+/;  # match a,b,c,x,y,z, or a digit
2109     /^=item\s\p{IsDigit}/;        # match '=item',
2110                                   # followed by a space and a digit
2111
2112 Whew! That is all the rest of the characters and character classes.
2113
2114 =head2 Compiling and saving regular expressions
2115
2116 In Part 1 we mentioned that Perl compiles a regexp into a compact
2117 sequence of opcodes.  Thus, a compiled regexp is a data structure
2118 that can be stored once and used again and again.  The regexp quote
2119 C<qr//> does exactly that: C<qr/string/> compiles the C<string> as a
2120 regexp and transforms the result into a form that can be assigned to a
2121 variable:
2122
2123     $reg = qr/foo+bar?/;  # reg contains a compiled regexp
2124
2125 Then C<$reg> can be used as a regexp:
2126
2127     $x = "fooooba";
2128     $x =~ $reg;     # matches, just like /foo+bar?/
2129     $x =~ /$reg/;   # same thing, alternate form
2130
2131 C<$reg> can also be interpolated into a larger regexp:
2132
2133     $x =~ /(abc)?$reg/;  # still matches
2134
2135 As with the matching operator, the regexp quote can use different
2136 delimiters, I<e.g.>, C<qr!!>, C<qr{}> or C<qr~~>.  Apostrophes
2137 as delimiters (C<qr''>) inhibit any interpolation.
2138
2139 Pre-compiled regexps are useful for creating dynamic matches that
2140 don't need to be recompiled each time they are encountered.  Using
2141 pre-compiled regexps, we write a C<grep_step> program which greps
2142 for a sequence of patterns, advancing to the next pattern as soon
2143 as one has been satisfied.
2144
2145     % cat > grep_step
2146     #!/usr/bin/perl
2147     # grep_step - match <number> regexps, one after the other
2148     # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2149
2150     $number = shift;
2151     $regexp[$_] = shift foreach (0..$number-1);
2152     @compiled = map qr/$_/, @regexp;
2153     while ($line = <>) {
2154         if ($line =~ /$compiled[0]/) {
2155             print $line;
2156             shift @compiled;
2157             last unless @compiled;
2158         }
2159     }
2160     ^D
2161
2162     % grep_step 3 shift print last grep_step
2163     $number = shift;
2164             print $line;
2165             last unless @compiled;
2166
2167 Storing pre-compiled regexps in an array C<@compiled> allows us to
2168 simply loop through the regexps without any recompilation, thus gaining
2169 flexibility without sacrificing speed.
2170
2171
2172 =head2 Composing regular expressions at runtime
2173
2174 Backtracking is more efficient than repeated tries with different regular
2175 expressions.  If there are several regular expressions and a match with
2176 any of them is acceptable, then it is possible to combine them into a set
2177 of alternatives.  If the individual expressions are input data, this
2178 can be done by programming a join operation.  We'll exploit this idea in
2179 an improved version of the C<simple_grep> program: a program that matches
2180 multiple patterns:
2181
2182     % cat > multi_grep
2183     #!/usr/bin/perl
2184     # multi_grep - match any of <number> regexps
2185     # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
2186
2187     $number = shift;
2188     $regexp[$_] = shift foreach (0..$number-1);
2189     $pattern = join '|', @regexp;
2190
2191     while ($line = <>) {
2192         print $line if $line =~ /$pattern/;
2193     }
2194     ^D
2195
2196     % multi_grep 2 shift for multi_grep
2197     $number = shift;
2198     $regexp[$_] = shift foreach (0..$number-1);
2199
2200 Sometimes it is advantageous to construct a pattern from the I<input>
2201 that is to be analyzed and use the permissible values on the left
2202 hand side of the matching operations.  As an example for this somewhat
2203 paradoxical situation, let's assume that our input contains a command
2204 verb which should match one out of a set of available command verbs,
2205 with the additional twist that commands may be abbreviated as long as
2206 the given string is unique. The program below demonstrates the basic
2207 algorithm.
2208
2209     % cat > keymatch
2210     #!/usr/bin/perl
2211     $kwds = 'copy compare list print';
2212     while( $cmd = <> ){
2213         $cmd =~ s/^\s+|\s+$//g;  # trim leading and trailing spaces
2214         if( ( @matches = $kwds =~ /\b$cmd\w*/g ) == 1 ){
2215             print "command: '@matches'\n";
2216         } elsif( @matches == 0 ){
2217             print "no such command: '$cmd'\n";
2218         } else {
2219             print "not unique: '$cmd' (could be one of: @matches)\n";
2220         }
2221     }
2222     ^D
2223
2224     % keymatch
2225     li
2226     command: 'list'
2227     co
2228     not unique: 'co' (could be one of: copy compare)
2229     printer
2230     no such command: 'printer'
2231
2232 Rather than trying to match the input against the keywords, we match the
2233 combined set of keywords against the input.  The pattern matching
2234 operation S<C<$kwds =~ /\b($cmd\w*)/g>> does several things at the
2235 same time. It makes sure that the given command begins where a keyword
2236 begins (C<\b>). It tolerates abbreviations due to the added C<\w*>. It
2237 tells us the number of matches (C<scalar @matches>) and all the keywords
2238 that were actually matched.  You could hardly ask for more.
2239
2240 =head2 Embedding comments and modifiers in a regular expression
2241
2242 Starting with this section, we will be discussing Perl's set of
2243 I<extended patterns>.  These are extensions to the traditional regular
2244 expression syntax that provide powerful new tools for pattern
2245 matching.  We have already seen extensions in the form of the minimal
2246 matching constructs C<??>, C<*?>, C<+?>, C<{n,m}?>, and C<{n,}?>.  Most
2247 of the extensions below have the form C<(?char...)>, where the
2248 C<char> is a character that determines the type of extension.
2249
2250 The first extension is an embedded comment C<(?#text)>.  This embeds a
2251 comment into the regular expression without affecting its meaning.  The
2252 comment should not have any closing parentheses in the text.  An
2253 example is
2254
2255     /(?# Match an integer:)[+-]?\d+/;
2256
2257 This style of commenting has been largely superseded by the raw,
2258 freeform commenting that is allowed with the C</x> modifier.
2259
2260 Most modifiers, such as C</i>, C</m>, C</s> and C</x> (or any
2261 combination thereof) can also be embedded in
2262 a regexp using C<(?i)>, C<(?m)>, C<(?s)>, and C<(?x)>.  For instance,
2263
2264     /(?i)yes/;  # match 'yes' case insensitively
2265     /yes/i;     # same thing
2266     /(?x)(          # freeform version of an integer regexp
2267              [+-]?  # match an optional sign
2268              \d+    # match a sequence of digits
2269          )
2270     /x;
2271
2272 Embedded modifiers can have two important advantages over the usual
2273 modifiers.  Embedded modifiers allow a custom set of modifiers for
2274 I<each> regexp pattern.  This is great for matching an array of regexps
2275 that must have different modifiers:
2276
2277     $pattern[0] = '(?i)doctor';
2278     $pattern[1] = 'Johnson';
2279     ...
2280     while (<>) {
2281         foreach $patt (@pattern) {
2282             print if /$patt/;
2283         }
2284     }
2285
2286 The second advantage is that embedded modifiers (except C</p>, which
2287 modifies the entire regexp) only affect the regexp
2288 inside the group the embedded modifier is contained in.  So grouping
2289 can be used to localize the modifier's effects:
2290
2291     /Answer: ((?i)yes)/;  # matches 'Answer: yes', 'Answer: YES', etc.
2292
2293 Embedded modifiers can also turn off any modifiers already present
2294 by using, I<e.g.>, C<(?-i)>.  Modifiers can also be combined into
2295 a single expression, I<e.g.>, C<(?s-i)> turns on single line mode and
2296 turns off case insensitivity.
2297
2298 Embedded modifiers may also be added to a non-capturing grouping.
2299 C<(?i-m:regexp)> is a non-capturing grouping that matches C<regexp>
2300 case insensitively and turns off multi-line mode.
2301
2302
2303 =head2 Looking ahead and looking behind
2304
2305 This section concerns the lookahead and lookbehind assertions.  First,
2306 a little background.
2307
2308 In Perl regular expressions, most regexp elements "eat up" a certain
2309 amount of string when they match.  For instance, the regexp element
2310 C<[abc]> eats up one character of the string when it matches, in the
2311 sense that Perl moves to the next character position in the string
2312 after the match.  There are some elements, however, that don't eat up
2313 characters (advance the character position) if they match.  The examples
2314 we have seen so far are the anchors.  The anchor C<'^'> matches the
2315 beginning of the line, but doesn't eat any characters.  Similarly, the
2316 word boundary anchor C<\b> matches wherever a character matching C<\w>
2317 is next to a character that doesn't, but it doesn't eat up any
2318 characters itself.  Anchors are examples of I<zero-width assertions>:
2319 zero-width, because they consume
2320 no characters, and assertions, because they test some property of the
2321 string.  In the context of our walk in the woods analogy to regexp
2322 matching, most regexp elements move us along a trail, but anchors have
2323 us stop a moment and check our surroundings.  If the local environment
2324 checks out, we can proceed forward.  But if the local environment
2325 doesn't satisfy us, we must backtrack.
2326
2327 Checking the environment entails either looking ahead on the trail,
2328 looking behind, or both.  C<'^'> looks behind, to see that there are no
2329 characters before.  C<'$'> looks ahead, to see that there are no
2330 characters after.  C<\b> looks both ahead and behind, to see if the
2331 characters on either side differ in their "word-ness".
2332
2333 The lookahead and lookbehind assertions are generalizations of the
2334 anchor concept.  Lookahead and lookbehind are zero-width assertions
2335 that let us specify which characters we want to test for.  The
2336 lookahead assertion is denoted by C<(?=regexp)> or (starting in 5.32,
2337 experimentally in 5.28) C<(*pla:regexp)> or
2338 C<(*positive_lookahead:regexp)>; and the lookbehind assertion is denoted
2339 by C<< (?<=fixed-regexp) >> or (starting in 5.32, experimentally in
2340 5.28) C<(*plb:fixed-regexp)> or C<(*positive_lookbehind:fixed-regexp)>.
2341 Some examples are
2342
2343     $x = "I catch the housecat 'Tom-cat' with catnip";
2344     $x =~ /cat(*pla:\s)/;   # matches 'cat' in 'housecat'
2345     @catwords = ($x =~ /(?<=\s)cat\w+/g);  # matches,
2346                                            # $catwords[0] = 'catch'
2347                                            # $catwords[1] = 'catnip'
2348     $x =~ /\bcat\b/;  # matches 'cat' in 'Tom-cat'
2349     $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
2350                               # middle of $x
2351
2352 Note that the parentheses in these are
2353 non-capturing, since these are zero-width assertions.  Thus in the
2354 second regexp, the substrings captured are those of the whole regexp
2355 itself.  Lookahead can match arbitrary regexps, but
2356 lookbehind prior to 5.30 C<< (?<=fixed-regexp) >> only works for regexps
2357 of fixed width, I<i.e.>, a fixed number of characters long.  Thus
2358 C<< (?<=(ab|bc)) >> is fine, but C<< (?<=(ab)*) >> prior to 5.30 is not.
2359
2360 The negated versions of the lookahead and lookbehind assertions are
2361 denoted by C<(?!regexp)> and C<< (?<!fixed-regexp) >> respectively.
2362 Or, starting in 5.32 (experimentally in 5.28), C<(*nla:regexp)>,
2363 C<(*negative_lookahead:regexp)>, C<(*nlb:regexp)>, or
2364 C<(*negative_lookbehind:regexp)>.
2365 They evaluate true if the regexps do I<not> match:
2366
2367     $x = "foobar";
2368     $x =~ /foo(?!bar)/;  # doesn't match, 'bar' follows 'foo'
2369     $x =~ /foo(?!baz)/;  # matches, 'baz' doesn't follow 'foo'
2370     $x =~ /(?<!\s)foo/;  # matches, there is no \s before 'foo'
2371
2372 Here is an example where a string containing blank-separated words,
2373 numbers and single dashes is to be split into its components.
2374 Using C</\s+/> alone won't work, because spaces are not required between
2375 dashes, or a word or a dash. Additional places for a split are established
2376 by looking ahead and behind:
2377
2378     $str = "one two - --6-8";
2379     @toks = split / \s+              # a run of spaces
2380                   | (?<=\S) (?=-)    # any non-space followed by '-'
2381                   | (?<=-)  (?=\S)   # a '-' followed by any non-space
2382                   /x, $str;          # @toks = qw(one two - - - 6 - 8)
2383
2384 =head2 Using independent subexpressions to prevent backtracking
2385
2386 I<Independent subexpressions> (or atomic subexpressions) are regular
2387 expressions, in the context of a larger regular expression, that
2388 function independently of the larger regular expression.  That is, they
2389 consume as much or as little of the string as they wish without regard
2390 for the ability of the larger regexp to match.  Independent
2391 subexpressions are represented by
2392 C<< (?>regexp) >> or (starting in 5.32, experimentally in 5.28)
2393 C<(*atomic:regexp)>.  We can illustrate their behavior by first
2394 considering an ordinary regexp:
2395
2396     $x = "ab";
2397     $x =~ /a*ab/;  # matches
2398
2399 This obviously matches, but in the process of matching, the
2400 subexpression C<a*> first grabbed the C<'a'>.  Doing so, however,
2401 wouldn't allow the whole regexp to match, so after backtracking, C<a*>
2402 eventually gave back the C<'a'> and matched the empty string.  Here, what
2403 C<a*> matched was I<dependent> on what the rest of the regexp matched.
2404
2405 Contrast that with an independent subexpression:
2406
2407     $x =~ /(?>a*)ab/;  # doesn't match!
2408
2409 The independent subexpression C<< (?>a*) >> doesn't care about the rest
2410 of the regexp, so it sees an C<'a'> and grabs it.  Then the rest of the
2411 regexp C<ab> cannot match.  Because C<< (?>a*) >> is independent, there
2412 is no backtracking and the independent subexpression does not give
2413 up its C<'a'>.  Thus the match of the regexp as a whole fails.  A similar
2414 behavior occurs with completely independent regexps:
2415
2416     $x = "ab";
2417     $x =~ /a*/g;   # matches, eats an 'a'
2418     $x =~ /\Gab/g; # doesn't match, no 'a' available
2419
2420 Here C</g> and C<\G> create a "tag team" handoff of the string from
2421 one regexp to the other.  Regexps with an independent subexpression are
2422 much like this, with a handoff of the string to the independent
2423 subexpression, and a handoff of the string back to the enclosing
2424 regexp.
2425
2426 The ability of an independent subexpression to prevent backtracking
2427 can be quite useful.  Suppose we want to match a non-empty string
2428 enclosed in parentheses up to two levels deep.  Then the following
2429 regexp matches:
2430
2431     $x = "abc(de(fg)h";  # unbalanced parentheses
2432     $x =~ /\( ( [ ^ () ]+ | \( [ ^ () ]* \) )+ \)/xx;
2433
2434 The regexp matches an open parenthesis, one or more copies of an
2435 alternation, and a close parenthesis.  The alternation is two-way, with
2436 the first alternative C<[^()]+> matching a substring with no
2437 parentheses and the second alternative C<\([^()]*\)>  matching a
2438 substring delimited by parentheses.  The problem with this regexp is
2439 that it is pathological: it has nested indeterminate quantifiers
2440 of the form C<(a+|b)+>.  We discussed in Part 1 how nested quantifiers
2441 like this could take an exponentially long time to execute if there
2442 was no match possible.  To prevent the exponential blowup, we need to
2443 prevent useless backtracking at some point.  This can be done by
2444 enclosing the inner quantifier as an independent subexpression:
2445
2446     $x =~ /\( ( (?> [ ^ () ]+ ) | \([ ^ () ]* \) )+ \)/xx;
2447
2448 Here, C<< (?>[^()]+) >> breaks the degeneracy of string partitioning
2449 by gobbling up as much of the string as possible and keeping it.   Then
2450 match failures fail much more quickly.
2451
2452
2453 =head2 Conditional expressions
2454
2455 A I<conditional expression> is a form of if-then-else statement
2456 that allows one to choose which patterns are to be matched, based on
2457 some condition.  There are two types of conditional expression:
2458 C<(?(I<condition>)I<yes-regexp>)> and
2459 C<(?(condition)I<yes-regexp>|I<no-regexp>)>.
2460 C<(?(I<condition>)I<yes-regexp>)> is
2461 like an S<C<'if () {}'>> statement in Perl.  If the I<condition> is true,
2462 the I<yes-regexp> will be matched.  If the I<condition> is false, the
2463 I<yes-regexp> will be skipped and Perl will move onto the next regexp
2464 element.  The second form is like an S<C<'if () {} else {}'>> statement
2465 in Perl.  If the I<condition> is true, the I<yes-regexp> will be
2466 matched, otherwise the I<no-regexp> will be matched.
2467
2468 The I<condition> can have several forms.  The first form is simply an
2469 integer in parentheses C<(I<integer>)>.  It is true if the corresponding
2470 backreference C<\I<integer>> matched earlier in the regexp.  The same
2471 thing can be done with a name associated with a capture group, written
2472 as C<<< (E<lt>I<name>E<gt>) >>> or C<< ('I<name>') >>.  The second form is a bare
2473 zero-width assertion C<(?...)>, either a lookahead, a lookbehind, or a
2474 code assertion (discussed in the next section).  The third set of forms
2475 provides tests that return true if the expression is executed within
2476 a recursion (C<(R)>) or is being called from some capturing group,
2477 referenced either by number (C<(R1)>, C<(R2)>,...) or by name
2478 (C<(R&I<name>)>).
2479
2480 The integer or name form of the C<condition> allows us to choose,
2481 with more flexibility, what to match based on what matched earlier in the
2482 regexp. This searches for words of the form C<"$x$x"> or C<"$x$y$y$x">:
2483
2484     % simple_grep '^(\w+)(\w+)?(?(2)\g2\g1|\g1)$' /usr/dict/words
2485     beriberi
2486     coco
2487     couscous
2488     deed
2489     ...
2490     toot
2491     toto
2492     tutu
2493
2494 The lookbehind C<condition> allows, along with backreferences,
2495 an earlier part of the match to influence a later part of the
2496 match.  For instance,
2497
2498     /[ATGC]+(?(?<=AA)G|C)$/;
2499
2500 matches a DNA sequence such that it either ends in C<AAG>, or some
2501 other base pair combination and C<'C'>.  Note that the form is
2502 C<< (?(?<=AA)G|C) >> and not C<< (?((?<=AA))G|C) >>; for the
2503 lookahead, lookbehind or code assertions, the parentheses around the
2504 conditional are not needed.
2505
2506
2507 =head2 Defining named patterns
2508
2509 Some regular expressions use identical subpatterns in several places.
2510 Starting with Perl 5.10, it is possible to define named subpatterns in
2511 a section of the pattern so that they can be called up by name
2512 anywhere in the pattern.  This syntactic pattern for this definition
2513 group is C<< (?(DEFINE)(?<I<name>>I<pattern>)...) >>.  An insertion
2514 of a named pattern is written as C<(?&I<name>)>.
2515
2516 The example below illustrates this feature using the pattern for
2517 floating point numbers that was presented earlier on.  The three
2518 subpatterns that are used more than once are the optional sign, the
2519 digit sequence for an integer and the decimal fraction.  The C<DEFINE>
2520 group at the end of the pattern contains their definition.  Notice
2521 that the decimal fraction pattern is the first place where we can
2522 reuse the integer pattern.
2523
2524    /^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
2525       (?: [eE](?&osg)(?&int) )?
2526     $
2527     (?(DEFINE)
2528       (?<osg>[-+]?)         # optional sign
2529       (?<int>\d++)          # integer
2530       (?<dec>\.(?&int))     # decimal fraction
2531     )/x
2532
2533
2534 =head2 Recursive patterns
2535
2536 This feature (introduced in Perl 5.10) significantly extends the
2537 power of Perl's pattern matching.  By referring to some other
2538 capture group anywhere in the pattern with the construct
2539 C<(?I<group-ref>)>, the I<pattern> within the referenced group is used
2540 as an independent subpattern in place of the group reference itself.
2541 Because the group reference may be contained I<within> the group it
2542 refers to, it is now possible to apply pattern matching to tasks that
2543 hitherto required a recursive parser.
2544
2545 To illustrate this feature, we'll design a pattern that matches if
2546 a string contains a palindrome. (This is a word or a sentence that,
2547 while ignoring spaces, interpunctuation and case, reads the same backwards
2548 as forwards. We begin by observing that the empty string or a string
2549 containing just one word character is a palindrome. Otherwise it must
2550 have a word character up front and the same at its end, with another
2551 palindrome in between.
2552
2553     /(?: (\w) (?...Here be a palindrome...) \g{-1} | \w? )/x
2554
2555 Adding C<\W*> at either end to eliminate what is to be ignored, we already
2556 have the full pattern:
2557
2558     my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
2559     for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
2560         print "'$s' is a palindrome\n" if $s =~ /$pp/;
2561     }
2562
2563 In C<(?...)> both absolute and relative backreferences may be used.
2564 The entire pattern can be reinserted with C<(?R)> or C<(?0)>.
2565 If you prefer to name your groups, you can use C<(?&I<name>)> to
2566 recurse into that group.
2567
2568
2569 =head2 A bit of magic: executing Perl code in a regular expression
2570
2571 Normally, regexps are a part of Perl expressions.
2572 I<Code evaluation> expressions turn that around by allowing
2573 arbitrary Perl code to be a part of a regexp.  A code evaluation
2574 expression is denoted C<(?{I<code>})>, with I<code> a string of Perl
2575 statements.
2576
2577 Code expressions are zero-width assertions, and the value they return
2578 depends on their environment.  There are two possibilities: either the
2579 code expression is used as a conditional in a conditional expression
2580 C<(?(I<condition>)...)>, or it is not.  If the code expression is a
2581 conditional, the code is evaluated and the result (I<i.e.>, the result of
2582 the last statement) is used to determine truth or falsehood.  If the
2583 code expression is not used as a conditional, the assertion always
2584 evaluates true and the result is put into the special variable
2585 C<$^R>.  The variable C<$^R> can then be used in code expressions later
2586 in the regexp.  Here are some silly examples:
2587
2588     $x = "abcdef";
2589     $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
2590                                          # prints 'Hi Mom!'
2591     $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
2592                                          # no 'Hi Mom!'
2593
2594 Pay careful attention to the next example:
2595
2596     $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
2597                                          # no 'Hi Mom!'
2598                                          # but why not?
2599
2600 At first glance, you'd think that it shouldn't print, because obviously
2601 the C<ddd> isn't going to match the target string. But look at this
2602 example:
2603
2604     $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
2605                                             # but _does_ print
2606
2607 Hmm. What happened here? If you've been following along, you know that
2608 the above pattern should be effectively (almost) the same as the last one;
2609 enclosing the C<'d'> in a character class isn't going to change what it
2610 matches. So why does the first not print while the second one does?
2611
2612 The answer lies in the optimizations the regexp engine makes. In the first
2613 case, all the engine sees are plain old characters (aside from the
2614 C<?{}> construct). It's smart enough to realize that the string C<'ddd'>
2615 doesn't occur in our target string before actually running the pattern
2616 through. But in the second case, we've tricked it into thinking that our
2617 pattern is more complicated. It takes a look, sees our
2618 character class, and decides that it will have to actually run the
2619 pattern to determine whether or not it matches, and in the process of
2620 running it hits the print statement before it discovers that we don't
2621 have a match.
2622
2623 To take a closer look at how the engine does optimizations, see the
2624 section L</"Pragmas and debugging"> below.
2625
2626 More fun with C<?{}>:
2627
2628     $x =~ /(?{print "Hi Mom!";})/;       # matches,
2629                                          # prints 'Hi Mom!'
2630     $x =~ /(?{$c = 1;})(?{print "$c";})/;  # matches,
2631                                            # prints '1'
2632     $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
2633                                            # prints '1'
2634
2635 The bit of magic mentioned in the section title occurs when the regexp
2636 backtracks in the process of searching for a match.  If the regexp
2637 backtracks over a code expression and if the variables used within are
2638 localized using C<local>, the changes in the variables produced by the
2639 code expression are undone! Thus, if we wanted to count how many times
2640 a character got matched inside a group, we could use, I<e.g.>,
2641
2642     $x = "aaaa";
2643     $count = 0;  # initialize 'a' count
2644     $c = "bob";  # test if $c gets clobbered
2645     $x =~ /(?{local $c = 0;})         # initialize count
2646            ( a                        # match 'a'
2647              (?{local $c = $c + 1;})  # increment count
2648            )*                         # do this any number of times,
2649            aa                         # but match 'aa' at the end
2650            (?{$count = $c;})          # copy local $c var into $count
2651           /x;
2652     print "'a' count is $count, \$c variable is '$c'\n";
2653
2654 This prints
2655
2656     'a' count is 2, $c variable is 'bob'
2657
2658 If we replace the S<C< (?{local $c = $c + 1;})>> with
2659 S<C< (?{$c = $c + 1;})>>, the variable changes are I<not> undone
2660 during backtracking, and we get
2661
2662     'a' count is 4, $c variable is 'bob'
2663
2664 Note that only localized variable changes are undone.  Other side
2665 effects of code expression execution are permanent.  Thus
2666
2667     $x = "aaaa";
2668     $x =~ /(a(?{print "Yow\n";}))*aa/;
2669
2670 produces
2671
2672    Yow
2673    Yow
2674    Yow
2675    Yow
2676
2677 The result C<$^R> is automatically localized, so that it will behave
2678 properly in the presence of backtracking.
2679
2680 This example uses a code expression in a conditional to match a
2681 definite article, either C<'the'> in English or C<'der|die|das'> in
2682 German:
2683
2684     $lang = 'DE';  # use German
2685     ...
2686     $text = "das";
2687     print "matched\n"
2688         if $text =~ /(?(?{
2689                           $lang eq 'EN'; # is the language English?
2690                          })
2691                        the |             # if so, then match 'the'
2692                        (der|die|das)     # else, match 'der|die|das'
2693                      )
2694                     /xi;
2695
2696 Note that the syntax here is C<(?(?{...})I<yes-regexp>|I<no-regexp>)>, not
2697 C<(?((?{...}))I<yes-regexp>|I<no-regexp>)>.  In other words, in the case of a
2698 code expression, we don't need the extra parentheses around the
2699 conditional.
2700
2701 If you try to use code expressions where the code text is contained within
2702 an interpolated variable, rather than appearing literally in the pattern,
2703 Perl may surprise you:
2704
2705     $bar = 5;
2706     $pat = '(?{ 1 })';
2707     /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
2708     /foo(?{ 1 })$bar/;   # compiles ok, $bar interpolated
2709     /foo${pat}bar/;      # compile error!
2710
2711     $pat = qr/(?{ $foo = 1 })/;  # precompile code regexp
2712     /foo${pat}bar/;      # compiles ok
2713
2714 If a regexp has a variable that interpolates a code expression, Perl
2715 treats the regexp as an error. If the code expression is precompiled into
2716 a variable, however, interpolating is ok. The question is, why is this an
2717 error?
2718
2719 The reason is that variable interpolation and code expressions
2720 together pose a security risk.  The combination is dangerous because
2721 many programmers who write search engines often take user input and
2722 plug it directly into a regexp:
2723
2724     $regexp = <>;       # read user-supplied regexp
2725     $chomp $regexp;     # get rid of possible newline
2726     $text =~ /$regexp/; # search $text for the $regexp
2727
2728 If the C<$regexp> variable contains a code expression, the user could
2729 then execute arbitrary Perl code.  For instance, some joker could
2730 search for S<C<system('rm -rf *');>> to erase your files.  In this
2731 sense, the combination of interpolation and code expressions I<taints>
2732 your regexp.  So by default, using both interpolation and code
2733 expressions in the same regexp is not allowed.  If you're not
2734 concerned about malicious users, it is possible to bypass this
2735 security check by invoking S<C<use re 'eval'>>:
2736
2737     use re 'eval';       # throw caution out the door
2738     $bar = 5;
2739     $pat = '(?{ 1 })';
2740     /foo${pat}bar/;      # compiles ok
2741
2742 Another form of code expression is the I<pattern code expression>.
2743 The pattern code expression is like a regular code expression, except
2744 that the result of the code evaluation is treated as a regular
2745 expression and matched immediately.  A simple example is
2746
2747     $length = 5;
2748     $char = 'a';
2749     $x = 'aaaaabb';
2750     $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
2751
2752
2753 This final example contains both ordinary and pattern code
2754 expressions.  It detects whether a binary string C<1101010010001...> has a
2755 Fibonacci spacing 0,1,1,2,3,5,...  of the C<'1'>'s:
2756
2757     $x = "1101010010001000001";
2758     $z0 = ''; $z1 = '0';   # initial conditions
2759     print "It is a Fibonacci sequence\n"
2760         if $x =~ /^1         # match an initial '1'
2761                     (?:
2762                        ((??{ $z0 })) # match some '0'
2763                        1             # and then a '1'
2764                        (?{ $z0 = $z1; $z1 .= $^N; })
2765                     )+   # repeat as needed
2766                   $      # that is all there is
2767                  /x;
2768     printf "Largest sequence matched was %d\n", length($z1)-length($z0);
2769
2770 Remember that C<$^N> is set to whatever was matched by the last
2771 completed capture group. This prints
2772
2773     It is a Fibonacci sequence
2774     Largest sequence matched was 5
2775
2776 Ha! Try that with your garden variety regexp package...
2777
2778 Note that the variables C<$z0> and C<$z1> are not substituted when the
2779 regexp is compiled, as happens for ordinary variables outside a code
2780 expression.  Rather, the whole code block is parsed as perl code at the
2781 same time as perl is compiling the code containing the literal regexp
2782 pattern.
2783
2784 This regexp without the C</x> modifier is
2785
2786     /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
2787
2788 which shows that spaces are still possible in the code parts. Nevertheless,
2789 when working with code and conditional expressions, the extended form of
2790 regexps is almost necessary in creating and debugging regexps.
2791
2792
2793 =head2 Backtracking control verbs
2794
2795 Perl 5.10 introduced a number of control verbs intended to provide
2796 detailed control over the backtracking process, by directly influencing
2797 the regexp engine and by providing monitoring techniques.  See
2798 L<perlre/"Special Backtracking Control Verbs"> for a detailed
2799 description.
2800
2801 Below is just one example, illustrating the control verb C<(*FAIL)>,
2802 which may be abbreviated as C<(*F)>. If this is inserted in a regexp
2803 it will cause it to fail, just as it would at some
2804 mismatch between the pattern and the string. Processing
2805 of the regexp continues as it would after any "normal"
2806 failure, so that, for instance, the next position in the string or another
2807 alternative will be tried. As failing to match doesn't preserve capture
2808 groups or produce results, it may be necessary to use this in
2809 combination with embedded code.
2810
2811    %count = ();
2812    "supercalifragilisticexpialidocious" =~
2813        /([aeiou])(?{ $count{$1}++; })(*FAIL)/i;
2814    printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
2815
2816 The pattern begins with a class matching a subset of letters.  Whenever
2817 this matches, a statement like C<$count{'a'}++;> is executed, incrementing
2818 the letter's counter. Then C<(*FAIL)> does what it says, and
2819 the regexp engine proceeds according to the book: as long as the end of
2820 the string hasn't been reached, the position is advanced before looking
2821 for another vowel. Thus, match or no match makes no difference, and the
2822 regexp engine proceeds until the entire string has been inspected.
2823 (It's remarkable that an alternative solution using something like
2824
2825    $count{lc($_)}++ for split('', "supercalifragilisticexpialidocious");
2826    printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
2827
2828 is considerably slower.)
2829
2830
2831 =head2 Pragmas and debugging
2832
2833 Speaking of debugging, there are several pragmas available to control
2834 and debug regexps in Perl.  We have already encountered one pragma in
2835 the previous section, S<C<use re 'eval';>>, that allows variable
2836 interpolation and code expressions to coexist in a regexp.  The other
2837 pragmas are
2838
2839     use re 'taint';
2840     $tainted = <>;
2841     @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
2842
2843 The C<taint> pragma causes any substrings from a match with a tainted
2844 variable to be tainted as well.  This is not normally the case, as
2845 regexps are often used to extract the safe bits from a tainted
2846 variable.  Use C<taint> when you are not extracting safe bits, but are
2847 performing some other processing.  Both C<taint> and C<eval> pragmas
2848 are lexically scoped, which means they are in effect only until
2849 the end of the block enclosing the pragmas.
2850
2851     use re '/m';  # or any other flags
2852     $multiline_string =~ /^foo/; # /m is implied
2853
2854 The C<re '/flags'> pragma (introduced in Perl
2855 5.14) turns on the given regular expression flags
2856 until the end of the lexical scope.  See
2857 L<re/"'E<sol>flags' mode"> for more
2858 detail.
2859
2860     use re 'debug';
2861     /^(.*)$/s;       # output debugging info
2862
2863     use re 'debugcolor';
2864     /^(.*)$/s;       # output debugging info in living color
2865
2866 The global C<debug> and C<debugcolor> pragmas allow one to get
2867 detailed debugging info about regexp compilation and
2868 execution.  C<debugcolor> is the same as debug, except the debugging
2869 information is displayed in color on terminals that can display
2870 termcap color sequences.  Here is example output:
2871
2872     % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
2873     Compiling REx 'a*b+c'
2874     size 9 first at 1
2875        1: STAR(4)
2876        2:   EXACT <a>(0)
2877        4: PLUS(7)
2878        5:   EXACT <b>(0)
2879        7: EXACT <c>(9)
2880        9: END(0)
2881     floating 'bc' at 0..2147483647 (checking floating) minlen 2
2882     Guessing start of match, REx 'a*b+c' against 'abc'...
2883     Found floating substr 'bc' at offset 1...
2884     Guessed: match at offset 0
2885     Matching REx 'a*b+c' against 'abc'
2886       Setting an EVAL scope, savestack=3
2887        0 <> <abc>           |  1:  STAR
2888                              EXACT <a> can match 1 times out of 32767...
2889       Setting an EVAL scope, savestack=3
2890        1 <a> <bc>           |  4:    PLUS
2891                              EXACT <b> can match 1 times out of 32767...
2892       Setting an EVAL scope, savestack=3
2893        2 <ab> <c>           |  7:      EXACT <c>
2894        3 <abc> <>           |  9:      END
2895     Match successful!
2896     Freeing REx: 'a*b+c'
2897
2898 If you have gotten this far into the tutorial, you can probably guess
2899 what the different parts of the debugging output tell you.  The first
2900 part
2901
2902     Compiling REx 'a*b+c'
2903     size 9 first at 1
2904        1: STAR(4)
2905        2:   EXACT <a>(0)
2906        4: PLUS(7)
2907        5:   EXACT <b>(0)
2908        7: EXACT <c>(9)
2909        9: END(0)
2910
2911 describes the compilation stage.  C<STAR(4)> means that there is a
2912 starred object, in this case C<'a'>, and if it matches, goto line 4,
2913 I<i.e.>, C<PLUS(7)>.  The middle lines describe some heuristics and
2914 optimizations performed before a match:
2915
2916     floating 'bc' at 0..2147483647 (checking floating) minlen 2
2917     Guessing start of match, REx 'a*b+c' against 'abc'...
2918     Found floating substr 'bc' at offset 1...
2919     Guessed: match at offset 0
2920
2921 Then the match is executed and the remaining lines describe the
2922 process:
2923
2924     Matching REx 'a*b+c' against 'abc'
2925       Setting an EVAL scope, savestack=3
2926        0 <> <abc>           |  1:  STAR
2927                              EXACT <a> can match 1 times out of 32767...
2928       Setting an EVAL scope, savestack=3
2929        1 <a> <bc>           |  4:    PLUS
2930                              EXACT <b> can match 1 times out of 32767...
2931       Setting an EVAL scope, savestack=3
2932        2 <ab> <c>           |  7:      EXACT <c>
2933        3 <abc> <>           |  9:      END
2934     Match successful!
2935     Freeing REx: 'a*b+c'
2936
2937 Each step is of the form S<C<< n <x> <y> >>>, with C<< <x> >> the
2938 part of the string matched and C<< <y> >> the part not yet
2939 matched.  The S<C<< |  1:  STAR >>> says that Perl is at line number 1
2940 in the compilation list above.  See
2941 L<perldebguts/"Debugging Regular Expressions"> for much more detail.
2942
2943 An alternative method of debugging regexps is to embed C<print>
2944 statements within the regexp.  This provides a blow-by-blow account of
2945 the backtracking in an alternation:
2946
2947     "that this" =~ m@(?{print "Start at position ", pos, "\n";})
2948                      t(?{print "t1\n";})
2949                      h(?{print "h1\n";})
2950                      i(?{print "i1\n";})
2951                      s(?{print "s1\n";})
2952                          |
2953                      t(?{print "t2\n";})
2954                      h(?{print "h2\n";})
2955                      a(?{print "a2\n";})
2956                      t(?{print "t2\n";})
2957                      (?{print "Done at position ", pos, "\n";})
2958                     @x;
2959
2960 prints
2961
2962     Start at position 0
2963     t1
2964     h1
2965     t2
2966     h2
2967     a2
2968     t2
2969     Done at position 4
2970
2971 =head1 SEE ALSO
2972
2973 This is just a tutorial.  For the full story on Perl regular
2974 expressions, see the L<perlre> regular expressions reference page.
2975
2976 For more information on the matching C<m//> and substitution C<s///>
2977 operators, see L<perlop/"Regexp Quote-Like Operators">.  For
2978 information on the C<split> operation, see L<perlfunc/split>.
2979
2980 For an excellent all-around resource on the care and feeding of
2981 regular expressions, see the book I<Mastering Regular Expressions> by
2982 Jeffrey Friedl (published by O'Reilly, ISBN 1556592-257-3).
2983
2984 =head1 AUTHOR AND COPYRIGHT
2985
2986 Copyright (c) 2000 Mark Kvale.
2987 All rights reserved.
2988 Now maintained by Perl porters.
2989
2990 This document may be distributed under the same terms as Perl itself.
2991
2992 =head2 Acknowledgments
2993
2994 The inspiration for the stop codon DNA example came from the ZIP
2995 code example in chapter 7 of I<Mastering Regular Expressions>.
2996
2997 The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
2998 Haworth, Ronald J Kimball, and Joe Smith for all their helpful
2999 comments.
3000
3001 =cut
3002