Re: \Q doesn't work in interpolated regular expressions
[p5sagit/p5-mst-13.2.git] / pod / perlre.pod
1 =head1 NAME
2
3 perlre - Perl regular expressions
4
5 =head1 DESCRIPTION
6
7 This page describes the syntax of regular expressions in Perl.  For a
8 description of how to I<use> regular expressions in matching
9 operations, plus various examples of the same, see discussion
10 of C<m//>, C<s///>, C<qr//> and C<??> in L<perlop/"Regexp Quote-Like Operators">.
11
12 The matching operations can have various modifiers.  The modifiers
13 that relate to the interpretation of the regular expression inside
14 are listed below.  For the modifiers that alter the way a regular expression
15 is used by Perl, see L<perlop/"Regexp Quote-Like Operators"> and 
16 L<perlop/"Gory details of parsing quoted constructs">.
17
18 =over 4
19
20 =item i
21
22 Do case-insensitive pattern matching.
23
24 If C<use locale> is in effect, the case map is taken from the current
25 locale.  See L<perllocale>.
26
27 =item m
28
29 Treat string as multiple lines.  That is, change "^" and "$" from matching
30 at only the very start or end of the string to the start or end of any
31 line anywhere within the string,
32
33 =item s
34
35 Treat string as single line.  That is, change "." to match any character
36 whatsoever, even a newline, which it normally would not match.
37
38 The C</s> and C</m> modifiers both override the C<$*> setting.  That is, no matter
39 what C<$*> contains, C</s> without C</m> will force "^" to match only at the
40 beginning of the string and "$" to match only at the end (or just before a
41 newline at the end) of the string.  Together, as /ms, they let the "." match
42 any character whatsoever, while yet allowing "^" and "$" to match,
43 respectively, just after and just before newlines within the string.
44
45 =item x
46
47 Extend your pattern's legibility by permitting whitespace and comments.
48
49 =back
50
51 These are usually written as "the C</x> modifier", even though the delimiter
52 in question might not actually be a slash.  In fact, any of these
53 modifiers may also be embedded within the regular expression itself using
54 the new C<(?...)> construct.  See below.
55
56 The C</x> modifier itself needs a little more explanation.  It tells
57 the regular expression parser to ignore whitespace that is neither
58 backslashed nor within a character class.  You can use this to break up
59 your regular expression into (slightly) more readable parts.  The C<#>
60 character is also treated as a metacharacter introducing a comment,
61 just as in ordinary Perl code.  This also means that if you want real
62 whitespace or C<#> characters in the pattern (outside of a character
63 class, where they are unaffected by C</x>), that you'll either have to 
64 escape them or encode them using octal or hex escapes.  Taken together,
65 these features go a long way towards making Perl's regular expressions
66 more readable.  Note that you have to be careful not to include the
67 pattern delimiter in the comment--perl has no way of knowing you did
68 not intend to close the pattern early.  See the C-comment deletion code
69 in L<perlop>.
70
71 =head2 Regular Expressions
72
73 The patterns used in pattern matching are regular expressions such as
74 those supplied in the Version 8 regex routines.  (In fact, the
75 routines are derived (distantly) from Henry Spencer's freely
76 redistributable reimplementation of the V8 routines.)
77 See L<Version 8 Regular Expressions> for details.
78
79 In particular the following metacharacters have their standard I<egrep>-ish
80 meanings:
81
82     \   Quote the next metacharacter
83     ^   Match the beginning of the line
84     .   Match any character (except newline)
85     $   Match the end of the line (or before newline at the end)
86     |   Alternation
87     ()  Grouping
88     []  Character class
89
90 By default, the "^" character is guaranteed to match at only the
91 beginning of the string, the "$" character at only the end (or before the
92 newline at the end) and Perl does certain optimizations with the
93 assumption that the string contains only one line.  Embedded newlines
94 will not be matched by "^" or "$".  You may, however, wish to treat a
95 string as a multi-line buffer, such that the "^" will match after any
96 newline within the string, and "$" will match before any newline.  At the
97 cost of a little more overhead, you can do this by using the /m modifier
98 on the pattern match operator.  (Older programs did this by setting C<$*>,
99 but this practice is now deprecated.)
100
101 To facilitate multi-line substitutions, the "." character never matches a
102 newline unless you use the C</s> modifier, which in effect tells Perl to pretend
103 the string is a single line--even if it isn't.  The C</s> modifier also
104 overrides the setting of C<$*>, in case you have some (badly behaved) older
105 code that sets it in another module.
106
107 The following standard quantifiers are recognized:
108
109     *      Match 0 or more times
110     +      Match 1 or more times
111     ?      Match 1 or 0 times
112     {n}    Match exactly n times
113     {n,}   Match at least n times
114     {n,m}  Match at least n but not more than m times
115
116 (If a curly bracket occurs in any other context, it is treated
117 as a regular character.)  The "*" modifier is equivalent to C<{0,}>, the "+"
118 modifier to C<{1,}>, and the "?" modifier to C<{0,1}>.  n and m are limited
119 to integral values less than 65536.
120
121 By default, a quantified subpattern is "greedy", that is, it will match as
122 many times as possible (given a particular starting location) while still
123 allowing the rest of the pattern to match.  If you want it to match the
124 minimum number of times possible, follow the quantifier with a "?".  Note
125 that the meanings don't change, just the "greediness":
126
127     *?     Match 0 or more times
128     +?     Match 1 or more times
129     ??     Match 0 or 1 time
130     {n}?   Match exactly n times
131     {n,}?  Match at least n times
132     {n,m}? Match at least n but not more than m times
133
134 Because patterns are processed as double quoted strings, the following
135 also work:
136
137     \t          tab                   (HT, TAB)
138     \n          newline               (LF, NL)
139     \r          return                (CR)
140     \f          form feed             (FF)
141     \a          alarm (bell)          (BEL)
142     \e          escape (think troff)  (ESC)
143     \033        octal char (think of a PDP-11)
144     \x1B        hex char
145     \c[         control char
146     \l          lowercase next char (think vi)
147     \u          uppercase next char (think vi)
148     \L          lowercase till \E (think vi)
149     \U          uppercase till \E (think vi)
150     \E          end case modification (think vi)
151     \Q          quote (disable) pattern metacharacters till \E
152
153 If C<use locale> is in effect, the case map used by C<\l>, C<\L>, C<\u>
154 and C<\U> is taken from the current locale.  See L<perllocale>.
155
156 You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
157 An unescaped C<$> or C<@> interpolates the corresponding variable,
158 while escaping will cause the literal string C<\$> to be matched.
159 You'll need to write something like C<m/\Quser\E\@\Qhost/>.
160
161 In addition, Perl defines the following:
162
163     \w  Match a "word" character (alphanumeric plus "_")
164     \W  Match a non-word character
165     \s  Match a whitespace character
166     \S  Match a non-whitespace character
167     \d  Match a digit character
168     \D  Match a non-digit character
169
170 A C<\w> matches a single alphanumeric character, not a whole
171 word.  To match a word you'd need to say C<\w+>.  If C<use locale> is in
172 effect, the list of alphabetic characters generated by C<\w> is taken
173 from the current locale.  See L<perllocale>. You may use C<\w>, C<\W>,
174 C<\s>, C<\S>, C<\d>, and C<\D> within character classes (though not as
175 either end of a range).
176
177 Perl defines the following zero-width assertions:
178
179     \b  Match a word boundary
180     \B  Match a non-(word boundary)
181     \A  Match only at beginning of string
182     \Z  Match only at end of string, or before newline at the end
183     \z  Match only at end of string
184     \G  Match only where previous m//g left off (works only with /g)
185
186 A word boundary (C<\b>) is defined as a spot between two characters that
187 has a C<\w> on one side of it and a C<\W> on the other side of it (in
188 either order), counting the imaginary characters off the beginning and
189 end of the string as matching a C<\W>.  (Within character classes C<\b>
190 represents backspace rather than a word boundary.)  The C<\A> and C<\Z> are
191 just like "^" and "$", except that they won't match multiple times when the
192 C</m> modifier is used, while "^" and "$" will match at every internal line
193 boundary.  To match the actual end of the string, not ignoring newline,
194 you can use C<\z>.  The C<\G> assertion can be used to chain global
195 matches (using C<m//g>), as described in
196 L<perlop/"Regexp Quote-Like Operators">.
197
198 It is also useful when writing C<lex>-like scanners, when you have several
199 patterns that you want to match against consequent substrings of your
200 string, see the previous reference.
201 The actual location where C<\G> will match can also be influenced
202 by using C<pos()> as an lvalue.  See L<perlfunc/pos>.
203
204 When the bracketing construct C<( ... )> is used, \E<lt>digitE<gt> matches the
205 digit'th substring.  Outside of the pattern, always use "$" instead of "\"
206 in front of the digit.  (While the \E<lt>digitE<gt> notation can on rare occasion work
207 outside the current pattern, this should not be relied upon.  See the
208 WARNING below.) The scope of $E<lt>digitE<gt> (and C<$`>, C<$&>, and C<$'>)
209 extends to the end of the enclosing BLOCK or eval string, or to the next
210 successful pattern match, whichever comes first.  If you want to use
211 parentheses to delimit a subpattern (e.g., a set of alternatives) without
212 saving it as a subpattern, follow the ( with a ?:.
213
214 You may have as many parentheses as you wish.  If you have more
215 than 9 substrings, the variables $10, $11, ... refer to the
216 corresponding substring.  Within the pattern, \10, \11, etc. refer back
217 to substrings if there have been at least that many left parentheses before
218 the backreference.  Otherwise (for backward compatibility) \10 is the
219 same as \010, a backspace, and \11 the same as \011, a tab.  And so
220 on.  (\1 through \9 are always backreferences.)
221
222 C<$+> returns whatever the last bracket match matched.  C<$&> returns the
223 entire matched string.  (C<$0> used to return the same thing, but not any
224 more.)  C<$`> returns everything before the matched string.  C<$'> returns
225 everything after the matched string.  Examples:
226
227     s/^([^ ]*) *([^ ]*)/$2 $1/;     # swap first two words
228
229     if (/Time: (..):(..):(..)/) {
230         $hours = $1;
231         $minutes = $2;
232         $seconds = $3;
233     }
234
235 Once perl sees that you need one of C<$&>, C<$`> or C<$'> anywhere in
236 the program, it has to provide them on each and every pattern match.
237 This can slow your program down.  The same mechanism that handles
238 these provides for the use of $1, $2, etc., so you pay the same price
239 for each pattern that contains capturing parentheses. But if you never
240 use $&, etc., in your script, then patterns I<without> capturing
241 parentheses won't be penalized. So avoid $&, $', and $` if you can,
242 but if you can't (and some algorithms really appreciate them), once
243 you've used them once, use them at will, because you've already paid
244 the price.  As of 5.005, $& is not so costly as the other two.
245
246 Backslashed metacharacters in Perl are
247 alphanumeric, such as C<\b>, C<\w>, C<\n>.  Unlike some other regular
248 expression languages, there are no backslashed symbols that aren't
249 alphanumeric.  So anything that looks like \\, \(, \), \E<lt>, \E<gt>,
250 \{, or \} is always interpreted as a literal character, not a
251 metacharacter.  This was once used in a common idiom to disable or
252 quote the special meanings of regular expression metacharacters in a
253 string that you want to use for a pattern. Simply quote all
254 non-alphanumeric characters:
255
256     $pattern =~ s/(\W)/\\$1/g;
257
258 Now it is much more common to see either the quotemeta() function or
259 the C<\Q> escape sequence used to disable all metacharacters' special
260 meanings like this:
261
262     /$unquoted\Q$quoted\E$unquoted/
263
264 Perl defines a consistent extension syntax for regular expressions.
265 The syntax is a pair of parentheses with a question mark as the first
266 thing within the parentheses (this was a syntax error in older
267 versions of Perl).  The character after the question mark gives the
268 function of the extension.  Several extensions are already supported:
269
270 =over 10
271
272 =item C<(?#text)>
273
274 A comment.  The text is ignored.  If the C</x> switch is used to enable
275 whitespace formatting, a simple C<#> will suffice.  Note that perl closes
276 the comment as soon as it sees a C<)>, so there is no way to put a literal
277 C<)> in the comment.
278
279 =item C<(?:pattern)>
280
281 =item C<(?imsx-imsx:pattern)>
282
283 This is for clustering, not capturing; it groups subexpressions like
284 "()", but doesn't make backreferences as "()" does.  So
285
286     @fields = split(/\b(?:a|b|c)\b/)
287
288 is like
289
290     @fields = split(/\b(a|b|c)\b/)
291
292 but doesn't spit out extra fields.
293
294 The letters between C<?> and C<:> act as flags modifiers, see
295 L<C<(?imsx-imsx)>>.  In particular,
296
297     /(?s-i:more.*than).*million/i
298
299 is equivalent to more verbose
300
301     /(?:(?s-i)more.*than).*million/i
302
303 =item C<(?=pattern)>
304
305 A zero-width positive lookahead assertion.  For example, C</\w+(?=\t)/>
306 matches a word followed by a tab, without including the tab in C<$&>.
307
308 =item C<(?!pattern)>
309
310 A zero-width negative lookahead assertion.  For example C</foo(?!bar)/>
311 matches any occurrence of "foo" that isn't followed by "bar".  Note
312 however that lookahead and lookbehind are NOT the same thing.  You cannot
313 use this for lookbehind.
314
315 If you are looking for a "bar" that isn't preceded by a "foo", C</(?!foo)bar/>
316 will not do what you want.  That's because the C<(?!foo)> is just saying that
317 the next thing cannot be "foo"--and it's not, it's a "bar", so "foobar" will
318 match.  You would have to do something like C</(?!foo)...bar/> for that.   We
319 say "like" because there's the case of your "bar" not having three characters
320 before it.  You could cover that this way: C</(?:(?!foo)...|^.{0,2})bar/>.
321 Sometimes it's still easier just to say:
322
323     if (/bar/ && $` !~ /foo$/)
324
325 For lookbehind see below.
326
327 =item C<(?E<lt>=pattern)>
328
329 A zero-width positive lookbehind assertion.  For example, C</(?E<lt>=\t)\w+/>
330 matches a word following a tab, without including the tab in C<$&>.
331 Works only for fixed-width lookbehind.
332
333 =item C<(?<!pattern)>
334
335 A zero-width negative lookbehind assertion.  For example C</(?<!bar)foo/>
336 matches any occurrence of "foo" that isn't following "bar".  
337 Works only for fixed-width lookbehind.
338
339 =item C<(?{ code })>
340
341 Experimental "evaluate any Perl code" zero-width assertion.  Always
342 succeeds.  C<code> is not interpolated.  Currently the rules to
343 determine where the C<code> ends are somewhat convoluted.
344
345 Owing to the risks to security, this is only available when the
346 C<use re 'eval'> pragma is used, and then only for patterns that don't
347 have any variables that must be interpolated at run time.
348
349 The C<code> is properly scoped in the following sense: if the assertion
350 is backtracked (compare L<"Backtracking">), all the changes introduced after
351 C<local>isation are undone, so
352
353   $_ = 'a' x 8;
354   m< 
355      (?{ $cnt = 0 })                    # Initialize $cnt.
356      (
357        a 
358        (?{
359            local $cnt = $cnt + 1;       # Update $cnt, backtracking-safe.
360        })
361      )*  
362      aaaa
363      (?{ $res = $cnt })                 # On success copy to non-localized
364                                         # location.
365    >x;
366
367 will set C<$res = 4>.  Note that after the match $cnt returns to the globally
368 introduced value 0, since the scopes which restrict C<local> statements
369 are unwound.
370
371 This assertion may be used as L<C<(?(condition)yes-pattern|no-pattern)>>
372 switch.  If I<not> used in this way, the result of evaluation of C<code>
373 is put into variable $^R.  This happens immediately, so $^R can be used from
374 other C<(?{ code })> assertions inside the same regular expression.
375
376 The above assignment to $^R is properly localized, thus the old value of $^R
377 is restored if the assertion is backtracked (compare L<"Backtracking">).
378
379 =item C<(?E<gt>pattern)>
380
381 An "independent" subexpression.  Matches the substring that a
382 I<standalone> C<pattern> would match if anchored at the given position,
383 B<and only this substring>.
384
385 Say, C<^(?E<gt>a*)ab> will never match, since C<(?E<gt>a*)> (anchored
386 at the beginning of string, as above) will match I<all> characters
387 C<a> at the beginning of string, leaving no C<a> for C<ab> to match.
388 In contrast, C<a*ab> will match the same as C<a+b>, since the match of
389 the subgroup C<a*> is influenced by the following group C<ab> (see
390 L<"Backtracking">).  In particular, C<a*> inside C<a*ab> will match
391 less characters that a standalone C<a*>, since this makes the tail match.
392
393 An effect similar to C<(?E<gt>pattern)> may be achieved by
394
395    (?=(pattern))\1
396
397 since the lookahead is in I<"logical"> context, thus matches the same
398 substring as a standalone C<a+>.  The following C<\1> eats the matched
399 string, thus making a zero-length assertion into an analogue of
400 C<(?>...)>.  (The difference between these two constructs is that the
401 second one uses a catching group, thus shifting ordinals of
402 backreferences in the rest of a regular expression.)
403
404 This construct is useful for optimizations of "eternal"
405 matches, because it will not backtrack (see L<"Backtracking">).  
406
407     m{  \( ( 
408          [^()]+ 
409        | 
410          \( [^()]* \)
411        )+
412         \) 
413     }x
414
415 That will efficiently match a nonempty group with matching
416 two-or-less-level-deep parentheses.  However, if there is no such group,
417 it will take virtually forever on a long string.  That's because there are
418 so many different ways to split a long string into several substrings.
419 This is essentially what C<(.+)+> is doing, and this is a subpattern
420 of the above pattern.  Consider that C<((()aaaaaaaaaaaaaaaaaa> on the
421 pattern above detects no-match in several seconds, but that  each extra
422 letter doubles this time.  This exponential performance will make it
423 appear that your program has hung.
424
425 However, a tiny modification of this pattern 
426
427     m{ \( ( 
428          (?> [^()]+ )
429        | 
430          \( [^()]* \)
431        )+
432         \) 
433     }x
434
435 which uses C<(?E<gt>...)> matches exactly when the one above does (verifying
436 this yourself would be a productive exercise), but finishes in a fourth
437 the time when used on a similar string with 1000000 C<a>s.  Be aware,
438 however, that this pattern currently triggers a warning message under
439 B<-w> saying it C<"matches the null string many times">):
440
441 On simple groups, such as the pattern C<(?> [^()]+ )>, a comparable
442 effect may be achieved by negative lookahead, as in C<[^()]+ (?! [^()] )>.
443 This was only 4 times slower on a string with 1000000 C<a>s.
444
445 =item C<(?(condition)yes-pattern|no-pattern)>
446
447 =item C<(?(condition)yes-pattern)>
448
449 Conditional expression.  C<(condition)> should be either an integer in
450 parentheses (which is valid if the corresponding pair of parentheses
451 matched), or lookahead/lookbehind/evaluate zero-width assertion.
452
453 Say,
454
455     m{ ( \( )? 
456       [^()]+ 
457        (?(1) \) ) 
458     }x
459
460 matches a chunk of non-parentheses, possibly included in parentheses
461 themselves.
462
463 =item C<(?imsx-imsx)>
464
465 One or more embedded pattern-match modifiers.  This is particularly
466 useful for patterns that are specified in a table somewhere, some of
467 which want to be case sensitive, and some of which don't.  The case
468 insensitive ones need to include merely C<(?i)> at the front of the
469 pattern.  For example:
470
471     $pattern = "foobar";
472     if ( /$pattern/i ) { } 
473
474     # more flexible:
475
476     $pattern = "(?i)foobar";
477     if ( /$pattern/ ) { } 
478
479 Letters after C<-> switch modifiers off.
480
481 These modifiers are localized inside an enclosing group (if any).  Say,
482
483     ( (?i) blah ) \s+ \1
484
485 (assuming C<x> modifier, and no C<i> modifier outside of this group)
486 will match a repeated (I<including the case>!) word C<blah> in any
487 case.
488
489 =back
490
491 A question mark was chosen for this and for the new minimal-matching
492 construct because 1) question mark is pretty rare in older regular
493 expressions, and 2) whenever you see one, you should stop and "question"
494 exactly what is going on.  That's psychology...
495
496 =head2 Backtracking
497
498 A fundamental feature of regular expression matching involves the
499 notion called I<backtracking>, which is currently used (when needed)
500 by all regular expression quantifiers, namely C<*>, C<*?>, C<+>,
501 C<+?>, C<{n,m}>, and C<{n,m}?>.
502
503 For a regular expression to match, the I<entire> regular expression must
504 match, not just part of it.  So if the beginning of a pattern containing a
505 quantifier succeeds in a way that causes later parts in the pattern to
506 fail, the matching engine backs up and recalculates the beginning
507 part--that's why it's called backtracking.
508
509 Here is an example of backtracking:  Let's say you want to find the
510 word following "foo" in the string "Food is on the foo table.":
511
512     $_ = "Food is on the foo table.";
513     if ( /\b(foo)\s+(\w+)/i ) {
514         print "$2 follows $1.\n";
515     }
516
517 When the match runs, the first part of the regular expression (C<\b(foo)>)
518 finds a possible match right at the beginning of the string, and loads up
519 $1 with "Foo".  However, as soon as the matching engine sees that there's
520 no whitespace following the "Foo" that it had saved in $1, it realizes its
521 mistake and starts over again one character after where it had the
522 tentative match.  This time it goes all the way until the next occurrence
523 of "foo". The complete regular expression matches this time, and you get
524 the expected output of "table follows foo."
525
526 Sometimes minimal matching can help a lot.  Imagine you'd like to match
527 everything between "foo" and "bar".  Initially, you write something
528 like this:
529
530     $_ =  "The food is under the bar in the barn.";
531     if ( /foo(.*)bar/ ) {
532         print "got <$1>\n";
533     }
534
535 Which perhaps unexpectedly yields:
536
537   got <d is under the bar in the >
538
539 That's because C<.*> was greedy, so you get everything between the
540 I<first> "foo" and the I<last> "bar".  In this case, it's more effective
541 to use minimal matching to make sure you get the text between a "foo"
542 and the first "bar" thereafter.
543
544     if ( /foo(.*?)bar/ ) { print "got <$1>\n" }
545   got <d is under the >
546
547 Here's another example: let's say you'd like to match a number at the end
548 of a string, and you also want to keep the preceding part the match.
549 So you write this:
550
551     $_ = "I have 2 numbers: 53147";
552     if ( /(.*)(\d*)/ ) {                                # Wrong!
553         print "Beginning is <$1>, number is <$2>.\n";
554     }
555
556 That won't work at all, because C<.*> was greedy and gobbled up the
557 whole string. As C<\d*> can match on an empty string the complete
558 regular expression matched successfully.
559
560     Beginning is <I have 2 numbers: 53147>, number is <>.
561
562 Here are some variants, most of which don't work:
563
564     $_ = "I have 2 numbers: 53147";
565     @pats = qw{
566         (.*)(\d*)
567         (.*)(\d+)
568         (.*?)(\d*)
569         (.*?)(\d+)
570         (.*)(\d+)$
571         (.*?)(\d+)$
572         (.*)\b(\d+)$
573         (.*\D)(\d+)$
574     };
575
576     for $pat (@pats) {
577         printf "%-12s ", $pat;
578         if ( /$pat/ ) {
579             print "<$1> <$2>\n";
580         } else {
581             print "FAIL\n";
582         }
583     }
584
585 That will print out:
586
587     (.*)(\d*)    <I have 2 numbers: 53147> <>
588     (.*)(\d+)    <I have 2 numbers: 5314> <7>
589     (.*?)(\d*)   <> <>
590     (.*?)(\d+)   <I have > <2>
591     (.*)(\d+)$   <I have 2 numbers: 5314> <7>
592     (.*?)(\d+)$  <I have 2 numbers: > <53147>
593     (.*)\b(\d+)$ <I have 2 numbers: > <53147>
594     (.*\D)(\d+)$ <I have 2 numbers: > <53147>
595
596 As you see, this can be a bit tricky.  It's important to realize that a
597 regular expression is merely a set of assertions that gives a definition
598 of success.  There may be 0, 1, or several different ways that the
599 definition might succeed against a particular string.  And if there are
600 multiple ways it might succeed, you need to understand backtracking to
601 know which variety of success you will achieve.
602
603 When using lookahead assertions and negations, this can all get even
604 tricker.  Imagine you'd like to find a sequence of non-digits not
605 followed by "123".  You might try to write that as
606
607         $_ = "ABC123";
608         if ( /^\D*(?!123)/ ) {                          # Wrong!
609             print "Yup, no 123 in $_\n";
610         }
611
612 But that isn't going to match; at least, not the way you're hoping.  It
613 claims that there is no 123 in the string.  Here's a clearer picture of
614 why it that pattern matches, contrary to popular expectations:
615
616     $x = 'ABC123' ;
617     $y = 'ABC445' ;
618
619     print "1: got $1\n" if $x =~ /^(ABC)(?!123)/ ;
620     print "2: got $1\n" if $y =~ /^(ABC)(?!123)/ ;
621
622     print "3: got $1\n" if $x =~ /^(\D*)(?!123)/ ;
623     print "4: got $1\n" if $y =~ /^(\D*)(?!123)/ ;
624
625 This prints
626
627     2: got ABC
628     3: got AB
629     4: got ABC
630
631 You might have expected test 3 to fail because it seems to a more
632 general purpose version of test 1.  The important difference between
633 them is that test 3 contains a quantifier (C<\D*>) and so can use
634 backtracking, whereas test 1 will not.  What's happening is
635 that you've asked "Is it true that at the start of $x, following 0 or more
636 non-digits, you have something that's not 123?"  If the pattern matcher had
637 let C<\D*> expand to "ABC", this would have caused the whole pattern to
638 fail.
639 The search engine will initially match C<\D*> with "ABC".  Then it will
640 try to match C<(?!123> with "123", which of course fails.  But because
641 a quantifier (C<\D*>) has been used in the regular expression, the
642 search engine can backtrack and retry the match differently
643 in the hope of matching the complete regular expression.
644
645 The pattern really, I<really> wants to succeed, so it uses the
646 standard pattern back-off-and-retry and lets C<\D*> expand to just "AB" this
647 time.  Now there's indeed something following "AB" that is not
648 "123".  It's in fact "C123", which suffices.
649
650 We can deal with this by using both an assertion and a negation.  We'll
651 say that the first part in $1 must be followed by a digit, and in fact, it
652 must also be followed by something that's not "123".  Remember that the
653 lookaheads are zero-width expressions--they only look, but don't consume
654 any of the string in their match.  So rewriting this way produces what
655 you'd expect; that is, case 5 will fail, but case 6 succeeds:
656
657     print "5: got $1\n" if $x =~ /^(\D*)(?=\d)(?!123)/ ;
658     print "6: got $1\n" if $y =~ /^(\D*)(?=\d)(?!123)/ ;
659
660     6: got ABC
661
662 In other words, the two zero-width assertions next to each other work as though
663 they're ANDed together, just as you'd use any builtin assertions:  C</^$/>
664 matches only if you're at the beginning of the line AND the end of the
665 line simultaneously.  The deeper underlying truth is that juxtaposition in
666 regular expressions always means AND, except when you write an explicit OR
667 using the vertical bar.  C</ab/> means match "a" AND (then) match "b",
668 although the attempted matches are made at different positions because "a"
669 is not a zero-width assertion, but a one-width assertion.
670
671 One warning: particularly complicated regular expressions can take
672 exponential time to solve due to the immense number of possible ways they
673 can use backtracking to try match.  For example this will take a very long
674 time to run
675
676     /((a{0,5}){0,5}){0,5}/
677
678 And if you used C<*>'s instead of limiting it to 0 through 5 matches, then
679 it would take literally forever--or until you ran out of stack space.
680
681 A powerful tool for optimizing such beasts is "independent" groups,
682 which do not backtrace (see L<C<(?E<gt>pattern)>>).  Note also that
683 zero-length lookahead/lookbehind assertions will not backtrace to make
684 the tail match, since they are in "logical" context: only the fact
685 whether they match or not is considered relevant.  For an example
686 where side-effects of a lookahead I<might> have influenced the
687 following match, see L<C<(?E<gt>pattern)>>.
688
689 =head2 Version 8 Regular Expressions
690
691 In case you're not familiar with the "regular" Version 8 regex
692 routines, here are the pattern-matching rules not described above.
693
694 Any single character matches itself, unless it is a I<metacharacter>
695 with a special meaning described here or above.  You can cause
696 characters that normally function as metacharacters to be interpreted
697 literally by prefixing them with a "\" (e.g., "\." matches a ".", not any
698 character; "\\" matches a "\").  A series of characters matches that
699 series of characters in the target string, so the pattern C<blurfl>
700 would match "blurfl" in the target string.
701
702 You can specify a character class, by enclosing a list of characters
703 in C<[]>, which will match any one character from the list.  If the
704 first character after the "[" is "^", the class matches any character not
705 in the list.  Within a list, the "-" character is used to specify a
706 range, so that C<a-z> represents all characters between "a" and "z",
707 inclusive.  If you want "-" itself to be a member of a class, put it
708 at the start or end of the list, or escape it with a backslash.  (The
709 following all specify the same class of three characters: C<[-az]>,
710 C<[az-]>, and C<[a\-z]>.  All are different from C<[a-z]>, which
711 specifies a class containing twenty-six characters.)
712
713 Characters may be specified using a metacharacter syntax much like that
714 used in C: "\n" matches a newline, "\t" a tab, "\r" a carriage return,
715 "\f" a form feed, etc.  More generally, \I<nnn>, where I<nnn> is a string
716 of octal digits, matches the character whose ASCII value is I<nnn>.
717 Similarly, \xI<nn>, where I<nn> are hexadecimal digits, matches the
718 character whose ASCII value is I<nn>. The expression \cI<x> matches the
719 ASCII character control-I<x>.  Finally, the "." metacharacter matches any
720 character except "\n" (unless you use C</s>).
721
722 You can specify a series of alternatives for a pattern using "|" to
723 separate them, so that C<fee|fie|foe> will match any of "fee", "fie",
724 or "foe" in the target string (as would C<f(e|i|o)e>).  The
725 first alternative includes everything from the last pattern delimiter
726 ("(", "[", or the beginning of the pattern) up to the first "|", and
727 the last alternative contains everything from the last "|" to the next
728 pattern delimiter.  For this reason, it's common practice to include
729 alternatives in parentheses, to minimize confusion about where they
730 start and end.
731
732 Alternatives are tried from left to right, so the first
733 alternative found for which the entire expression matches, is the one that
734 is chosen. This means that alternatives are not necessarily greedy. For
735 example: when mathing C<foo|foot> against "barefoot", only the "foo"
736 part will match, as that is the first alternative tried, and it successfully
737 matches the target string. (This might not seem important, but it is
738 important when you are capturing matched text using parentheses.)
739
740 Also remember that "|" is interpreted as a literal within square brackets,
741 so if you write C<[fee|fie|foe]> you're really only matching C<[feio|]>.
742
743 Within a pattern, you may designate subpatterns for later reference by
744 enclosing them in parentheses, and you may refer back to the I<n>th
745 subpattern later in the pattern using the metacharacter \I<n>.
746 Subpatterns are numbered based on the left to right order of their
747 opening parenthesis.  A backreference matches whatever
748 actually matched the subpattern in the string being examined, not the
749 rules for that subpattern.  Therefore, C<(0|0x)\d*\s\1\d*> will
750 match "0x1234 0x4321", but not "0x1234 01234", because subpattern 1
751 actually matched "0x", even though the rule C<0|0x> could
752 potentially match the leading 0 in the second number.
753
754 =head2 WARNING on \1 vs $1
755
756 Some people get too used to writing things like:
757
758     $pattern =~ s/(\W)/\\\1/g;
759
760 This is grandfathered for the RHS of a substitute to avoid shocking the
761 B<sed> addicts, but it's a dirty habit to get into.  That's because in
762 PerlThink, the righthand side of a C<s///> is a double-quoted string.  C<\1> in
763 the usual double-quoted string means a control-A.  The customary Unix
764 meaning of C<\1> is kludged in for C<s///>.  However, if you get into the habit
765 of doing that, you get yourself into trouble if you then add an C</e>
766 modifier.
767
768     s/(\d+)/ \1 + 1 /eg;        # causes warning under -w
769
770 Or if you try to do
771
772     s/(\d+)/\1000/;
773
774 You can't disambiguate that by saying C<\{1}000>, whereas you can fix it with
775 C<${1}000>.  Basically, the operation of interpolation should not be confused
776 with the operation of matching a backreference.  Certainly they mean two
777 different things on the I<left> side of the C<s///>.
778
779 =head2 Repeated patterns matching zero-length substring
780
781 WARNING: Difficult material (and prose) ahead.  This section needs a rewrite.
782
783 Regular expressions provide a terse and powerful programming language.  As
784 with most other power tools, power comes together with the ability
785 to wreak havoc.
786
787 A common abuse of this power stems from the ability to make infinite
788 loops using regular expressions, with something as innocous as:
789
790     'foo' =~ m{ ( o? )* }x;
791
792 The C<o?> can match at the beginning of C<'foo'>, and since the position
793 in the string is not moved by the match, C<o?> would match again and again
794 due to the C<*> modifier.  Another common way to create a similar cycle
795 is with the looping modifier C<//g>:
796
797     @matches = ( 'foo' =~ m{ o? }xg );
798
799 or
800
801     print "match: <$&>\n" while 'foo' =~ m{ o? }xg;
802
803 or the loop implied by split().
804
805 However, long experience has shown that many programming tasks may
806 be significantly simplified by using repeated subexpressions which
807 may match zero-length substrings, with a simple example being:
808
809     @chars = split //, $string;           # // is not magic in split
810     ($whitewashed = $string) =~ s/()/ /g; # parens avoid magic s// /
811
812 Thus Perl allows the C</()/> construct, which I<forcefully breaks
813 the infinite loop>.  The rules for this are different for lower-level
814 loops given by the greedy modifiers C<*+{}>, and for higher-level
815 ones like the C</g> modifier or split() operator.
816
817 The lower-level loops are I<interrupted> when it is detected that a 
818 repeated expression did match a zero-length substring, thus
819
820    m{ (?: NON_ZERO_LENGTH | ZERO_LENGTH )* }x;
821
822 is made equivalent to 
823
824    m{   (?: NON_ZERO_LENGTH )* 
825       | 
826         (?: ZERO_LENGTH )? 
827     }x;
828
829 The higher level-loops preserve an additional state between iterations:
830 whether the last match was zero-length.  To break the loop, the following 
831 match after a zero-length match is prohibited to have a length of zero.
832 This prohibition interacts with backtracking (see L<"Backtracking">), 
833 and so the I<second best> match is chosen if the I<best> match is of
834 zero length.
835
836 Say,
837
838     $_ = 'bar';
839     s/\w??/<$&>/g;
840
841 results in C<"<><b><><a><><r><>">.  At each position of the string the best
842 match given by non-greedy C<??> is the zero-length match, and the I<second 
843 best> match is what is matched by C<\w>.  Thus zero-length matches
844 alternate with one-character-long matches.
845
846 Similarly, for repeated C<m/()/g> the second-best match is the match at the 
847 position one notch further in the string.
848
849 The additional state of being I<matched with zero-length> is associated to
850 the matched string, and is reset by each assignment to pos().
851
852 =head2 Creating custom RE engines
853
854 Overloaded constants (see L<overload>) provide a simple way to extend
855 the functionality of the RE engine.
856
857 Suppose that we want to enable a new RE escape-sequence C<\Y|> which
858 matches at boundary between white-space characters and non-whitespace
859 characters.  Note that C<(?=\S)(?<!\S)|(?!\S)(?<=\S)> matches exactly
860 at these positions, so we want to have each C<\Y|> in the place of the
861 more complicated version.  We can create a module C<customre> to do
862 this:
863
864     package customre;
865     use overload;
866
867     sub import {
868       shift;
869       die "No argument to customre::import allowed" if @_;
870       overload::constant 'qr' => \&convert;
871     }
872
873     sub invalid { die "/$_[0]/: invalid escape '\\$_[1]'"}
874
875     my %rules = ( '\\' => '\\', 
876                   'Y|' => qr/(?=\S)(?<!\S)|(?!\S)(?<=\S)/ );
877     sub convert {
878       my $re = shift;
879       $re =~ s{ 
880                 \\ ( \\ | Y . )
881               }
882               { $rules{$1} or invalid($re,$1) }sgex; 
883       return $re;
884     }
885
886 Now C<use customre> enables the new escape in constant regular
887 expressions, i.e., those without any runtime variable interpolations.
888 As documented in L<overload>, this conversion will work only over
889 literal parts of regular expressions.  For C<\Y|$re\Y|> the variable
890 part of this regular expression needs to be converted explicitly
891 (but only if the special meaning of C<\Y|> should be enabled inside $re):
892
893     use customre;
894     $re = <>;
895     chomp $re;
896     $re = customre::convert $re;
897     /\Y|$re\Y|/;
898
899 =head2 SEE ALSO
900
901 L<perlop/"Regexp Quote-Like Operators">.
902
903 L<perlop/"Gory details of parsing quoted constructs">.
904
905 L<perlfunc/pos>.
906
907 L<perllocale>.
908
909 I<Mastering Regular Expressions> (see L<perlbook>) by Jeffrey Friedl.