1PERLRETUT(1)           Perl Programmers Reference Guide           PERLRETUT(1)
2
3
4

NAME

6       perlretut - Perl regular expressions tutorial
7

DESCRIPTION

9       This page provides a basic tutorial on understanding, creating and
10       using regular expressions in Perl.  It serves as a complement to the
11       reference page on regular expressions perlre.  Regular expressions are
12       an integral part of the "m//", "s///", "qr//" and "split" operators and
13       so this tutorial also overlaps with "Regexp Quote-Like Operators" in
14       perlop and "split" in perlfunc.
15
16       Perl is widely renowned for excellence in text processing, and regular
17       expressions are one of the big factors behind this fame.  Perl regular
18       expressions display an efficiency and flexibility unknown in most other
19       computer languages.  Mastering even the basics of regular expressions
20       will allow you to manipulate text with surprising ease.
21
22       What is a regular expression?  At its most basic, a regular expression
23       is a template that is used to determine if a string has certain
24       characteristics.  The string is most often some text, such as a line,
25       sentence, web page, or even a whole book, but less commonly it could be
26       some binary data as well.  Suppose we want to determine if the text in
27       variable, $var contains the sequence of characters "m u s h r o o m"
28       (blanks added for legibility).  We can write in Perl
29
30        $var =~ m/mushroom/
31
32       The value of this expression will be TRUE if $var contains that
33       sequence of characters, and FALSE otherwise.  The portion enclosed in
34       '/' characters denotes the characteristic we are looking for.  We use
35       the term pattern for it.  The process of looking to see if the pattern
36       occurs in the string is called matching, and the "=~" operator along
37       with the "m//" tell Perl to try to match the pattern against the
38       string.  Note that the pattern is also a string, but a very special
39       kind of one, as we will see.  Patterns are in common use these 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, e.g., ""ls *.txt""
42       or ""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 "/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 simple concepts like conditionals and loops and are
53       no more difficult to understand than the corresponding "if"
54       conditionals and "while" loops in the Perl language itself.
55
56       This tutorial flattens the learning curve by discussing regular
57       expression concepts, along with their notation, one at a time and with
58       many examples.  The first part of the tutorial will progress from the
59       simplest word searches to the basic regular expression concepts.  If
60       you master the first part, you will have all the tools needed to solve
61       about 98% of your needs.  The second part of the tutorial is for those
62       comfortable with the basics and hungry for more power tools.  It
63       discusses the more advanced regular expression operators and introduces
64       the latest cutting-edge innovations.
65
66       A note: to save time, "regular expression" is often abbreviated as
67       regexp or regex.  Regexp is a more natural abbreviation than regex, but
68       is harder to pronounce.  The Perl pod documentation is evenly split on
69       regexp vs regex; in Perl, there is more than one way to abbreviate it.
70       We'll use regexp in this tutorial.
71
72       New in v5.22, "use re 'strict'" applies stricter rules than otherwise
73       when compiling regular expression patterns.  It can find things that,
74       while legal, may not be what you intended.
75

Part 1: The basics

77   Simple word matching
78       The simplest regexp is simply a word, or more generally, a string of
79       characters.  A regexp consisting of just a word matches any string that
80       contains that word:
81
82           "Hello World" =~ /World/;  # matches
83
84       What is this Perl statement all about? "Hello World" is a simple
85       double-quoted string.  "World" is the regular expression and the "//"
86       enclosing "/World/" tells Perl to search a string for a match.  The
87       operator "=~" associates the string with the regexp match and produces
88       a true value if the regexp matched, or false if the regexp did not
89       match.  In our case, "World" matches the second word in "Hello World",
90       so the expression is true.  Expressions like this are useful in
91       conditionals:
92
93           if ("Hello World" =~ /World/) {
94               print "It matches\n";
95           }
96           else {
97               print "It doesn't match\n";
98           }
99
100       There are useful variations on this theme.  The sense of the match can
101       be reversed by using the "!~" operator:
102
103           if ("Hello World" !~ /World/) {
104               print "It doesn't match\n";
105           }
106           else {
107               print "It matches\n";
108           }
109
110       The literal string in the regexp can be replaced by a variable:
111
112           my $greeting = "World";
113           if ("Hello World" =~ /$greeting/) {
114               print "It matches\n";
115           }
116           else {
117               print "It doesn't match\n";
118           }
119
120       If you're matching against the special default variable $_, the "$_ =~"
121       part can be omitted:
122
123           $_ = "Hello World";
124           if (/World/) {
125               print "It matches\n";
126           }
127           else {
128               print "It doesn't match\n";
129           }
130
131       And finally, the "//" default delimiters for a match can be changed to
132       arbitrary delimiters by putting an 'm' out front:
133
134           "Hello World" =~ m!World!;   # matches, delimited by '!'
135           "Hello World" =~ m{World};   # matches, note the matching '{}'
136           "/usr/bin/perl" =~ m"/perl"; # matches after '/usr/bin',
137                                        # '/' becomes an ordinary char
138
139       "/World/", "m!World!", and "m{World}" all represent the same thing.
140       When, e.g., the quote ('"') is used as a delimiter, the forward slash
141       '/' becomes an ordinary character and can be used in this regexp
142       without trouble.
143
144       Let's consider how different regexps would match "Hello World":
145
146           "Hello World" =~ /world/;  # doesn't match
147           "Hello World" =~ /o W/;    # matches
148           "Hello World" =~ /oW/;     # doesn't match
149           "Hello World" =~ /World /; # doesn't match
150
151       The first regexp "world" doesn't match because regexps are case-
152       sensitive.  The second regexp matches because the substring 'o W'
153       occurs in the string "Hello World".  The space character ' ' is treated
154       like any other character in a regexp and is needed to match in this
155       case.  The lack of a space character is the reason the third regexp
156       'oW' doesn't match.  The fourth regexp ""World "" doesn't match because
157       there is a space at the end of the regexp, but not at the end of the
158       string.  The lesson here is that regexps must match a part of the
159       string exactly in order for the statement to be true.
160
161       If a regexp matches in more than one place in the string, Perl will
162       always match at the earliest possible point in the string:
163
164           "Hello World" =~ /o/;       # matches 'o' in 'Hello'
165           "That hat is red" =~ /hat/; # matches 'hat' in 'That'
166
167       With respect to character matching, there are a few more points you
168       need to know about.   First of all, not all characters can be used "as
169       is" in a match.  Some characters, called metacharacters, are generally
170       reserved for use in regexp notation.  The metacharacters are
171
172           {}[]()^$.|*+?-#\
173
174       This list is not as definitive as it may appear (or be claimed to be in
175       other documentation).  For example, "#" is a metacharacter only when
176       the "/x" pattern modifier (described below) is used, and both "}" and
177       "]" are metacharacters only when paired with opening "{" or "["
178       respectively; other gotchas apply.
179
180       The significance of each of these will be explained in the rest of the
181       tutorial, but for now, it is important only to know that a
182       metacharacter can be matched as-is by putting a backslash before it:
183
184           "2+2=4" =~ /2+2/;    # doesn't match, + is a metacharacter
185           "2+2=4" =~ /2\+2/;   # matches, \+ is treated like an ordinary +
186           "The interval is [0,1)." =~ /[0,1)./     # is a syntax error!
187           "The interval is [0,1)." =~ /\[0,1\)\./  # matches
188           "#!/usr/bin/perl" =~ /#!\/usr\/bin\/perl/;  # matches
189
190       In the last regexp, the forward slash '/' is also backslashed, because
191       it is used to delimit the regexp.  This can lead to LTS (leaning
192       toothpick syndrome), however, and it is often more readable to change
193       delimiters.
194
195           "#!/usr/bin/perl" =~ m!#\!/usr/bin/perl!;  # easier to read
196
197       The backslash character '\' is a metacharacter itself and needs to be
198       backslashed:
199
200           'C:\WIN32' =~ /C:\\WIN/;   # matches
201
202       In situations where it doesn't make sense for a particular
203       metacharacter to mean what it normally does, it automatically loses its
204       metacharacter-ness and becomes an ordinary character that is to be
205       matched literally.  For example, the '}' is a metacharacter only when
206       it is the mate of a '{' metacharacter.  Otherwise it is treated as a
207       literal RIGHT CURLY BRACKET.  This may lead to unexpected results.
208       "use re 'strict'" can catch some of these.
209
210       In addition to the metacharacters, there are some ASCII characters
211       which don't have printable character equivalents and are instead
212       represented by escape sequences.  Common examples are "\t" for a tab,
213       "\n" for a newline, "\r" for a carriage return and "\a" for a bell (or
214       alert).  If your string is better thought of as a sequence of arbitrary
215       bytes, the octal escape sequence, e.g., "\033", or hexadecimal escape
216       sequence, e.g., "\x1B" may be a more natural representation for your
217       bytes.  Here are some examples of escapes:
218
219           "1000\t2000" =~ m(0\t2)   # matches
220           "1000\n2000" =~ /0\n20/   # matches
221           "1000\t2000" =~ /\000\t2/ # doesn't match, "0" ne "\000"
222           "cat"   =~ /\o{143}\x61\x74/ # matches in ASCII, but a weird way
223                                        # to spell cat
224
225       If you've been around Perl a while, all this talk of escape sequences
226       may seem familiar.  Similar escape sequences are used in double-quoted
227       strings and in fact the regexps in Perl are mostly treated as double-
228       quoted strings.  This means that variables can be used in regexps as
229       well.  Just like double-quoted strings, the values of the variables in
230       the regexp will be substituted in before the regexp is evaluated for
231       matching purposes.  So we have:
232
233           $foo = 'house';
234           'housecat' =~ /$foo/;      # matches
235           'cathouse' =~ /cat$foo/;   # matches
236           'housecat' =~ /${foo}cat/; # matches
237
238       So far, so good.  With the knowledge above you can already perform
239       searches with just about any literal string regexp you can dream up.
240       Here is a very simple emulation of the Unix grep program:
241
242           % cat > simple_grep
243           #!/usr/bin/perl
244           $regexp = shift;
245           while (<>) {
246               print if /$regexp/;
247           }
248           ^D
249
250           % chmod +x simple_grep
251
252           % simple_grep abba /usr/dict/words
253           Babbage
254           cabbage
255           cabbages
256           sabbath
257           Sabbathize
258           Sabbathizes
259           sabbatical
260           scabbard
261           scabbards
262
263       This program is easy to understand.  "#!/usr/bin/perl" is the standard
264       way to invoke a perl program from the shell.  "$regexp = shift;" saves
265       the first command line argument as the regexp to be used, leaving the
266       rest of the command line arguments to be treated as files.
267       "while (<>)" loops over all the lines in all the files.  For each line,
268       "print if /$regexp/;" prints the line if the regexp matches the line.
269       In this line, both "print" and "/$regexp/" use the default variable $_
270       implicitly.
271
272       With all of the regexps above, if the regexp matched anywhere in the
273       string, it was considered a match.  Sometimes, however, we'd like to
274       specify where in the string the regexp should try to match.  To do
275       this, we would use the anchor metacharacters '^' and '$'.  The anchor
276       '^' means match at the beginning of the string and the anchor '$' means
277       match at the end of the string, or before a newline at the end of the
278       string.  Here is how they are used:
279
280           "housekeeper" =~ /keeper/;    # matches
281           "housekeeper" =~ /^keeper/;   # doesn't match
282           "housekeeper" =~ /keeper$/;   # matches
283           "housekeeper\n" =~ /keeper$/; # matches
284
285       The second regexp doesn't match because '^' constrains "keeper" to
286       match only at the beginning of the string, but "housekeeper" has keeper
287       starting in the middle.  The third regexp does match, since the '$'
288       constrains "keeper" to match only at the end of the string.
289
290       When both '^' and '$' are used at the same time, the regexp has to
291       match both the beginning and the end of the string, i.e., the regexp
292       matches the whole string.  Consider
293
294           "keeper" =~ /^keep$/;      # doesn't match
295           "keeper" =~ /^keeper$/;    # matches
296           ""       =~ /^$/;          # ^$ matches an empty string
297
298       The first regexp doesn't match because the string has more to it than
299       "keep".  Since the second regexp is exactly the string, it matches.
300       Using both '^' and '$' in a regexp forces the complete string to match,
301       so it gives you complete control over which strings match and which
302       don't.  Suppose you are looking for a fellow named bert, off in a
303       string by himself:
304
305           "dogbert" =~ /bert/;   # matches, but not what you want
306
307           "dilbert" =~ /^bert/;  # doesn't match, but ..
308           "bertram" =~ /^bert/;  # matches, so still not good enough
309
310           "bertram" =~ /^bert$/; # doesn't match, good
311           "dilbert" =~ /^bert$/; # doesn't match, good
312           "bert"    =~ /^bert$/; # matches, perfect
313
314       Of course, in the case of a literal string, one could just as easily
315       use the string comparison "$string eq 'bert'" and it would be more
316       efficient.   The  "^...$" regexp really becomes useful when we add in
317       the more powerful regexp tools below.
318
319   Using character classes
320       Although one can already do quite a lot with the literal string regexps
321       above, we've only scratched the surface of regular expression
322       technology.  In this and subsequent sections we will introduce regexp
323       concepts (and associated metacharacter notations) that will allow a
324       regexp to represent not just a single character sequence, but a whole
325       class of them.
326
327       One such concept is that of a character class.  A character class
328       allows a set of possible characters, rather than just a single
329       character, to match at a particular point in a regexp.  You can define
330       your own custom character classes.  These are denoted by brackets
331       "[...]", with the set of characters to be possibly matched inside.
332       Here are some examples:
333
334           /cat/;       # matches 'cat'
335           /[bcr]at/;   # matches 'bat, 'cat', or 'rat'
336           /item[0123456789]/;  # matches 'item0' or ... or 'item9'
337           "abc" =~ /[cab]/;    # matches 'a'
338
339       In the last statement, even though 'c' is the first character in the
340       class, 'a' matches because the first character position in the string
341       is the earliest point at which the regexp can match.
342
343           /[yY][eE][sS]/;      # match 'yes' in a case-insensitive way
344                                # 'yes', 'Yes', 'YES', etc.
345
346       This regexp displays a common task: perform a case-insensitive match.
347       Perl provides a way of avoiding all those brackets by simply appending
348       an 'i' to the end of the match.  Then "/[yY][eE][sS]/;" can be
349       rewritten as "/yes/i;".  The 'i' stands for case-insensitive and is an
350       example of a modifier of the matching operation.  We will meet other
351       modifiers later in the tutorial.
352
353       We saw in the section above that there were ordinary characters, which
354       represented themselves, and special characters, which needed a
355       backslash '\' to represent themselves.  The same is true in a character
356       class, but the sets of ordinary and special characters inside a
357       character class are different than those outside a character class.
358       The special characters for a character class are "-]\^$" (and the
359       pattern delimiter, whatever it is).  ']' is special because it denotes
360       the end of a character class.  '$' is special because it denotes a
361       scalar variable.  '\' is special because it is used in escape
362       sequences, just like above.  Here is how the special characters "]$\"
363       are handled:
364
365          /[\]c]def/; # matches ']def' or 'cdef'
366          $x = 'bcr';
367          /[$x]at/;   # matches 'bat', 'cat', or 'rat'
368          /[\$x]at/;  # matches '$at' or 'xat'
369          /[\\$x]at/; # matches '\at', 'bat, 'cat', or 'rat'
370
371       The last two are a little tricky.  In "[\$x]", the backslash protects
372       the dollar sign, so the character class has two members '$' and 'x'.
373       In "[\\$x]", the backslash is protected, so $x is treated as a variable
374       and substituted in double quote fashion.
375
376       The special character '-' acts as a range operator within character
377       classes, so that a contiguous set of characters can be written as a
378       range.  With ranges, the unwieldy "[0123456789]" and "[abc...xyz]"
379       become the svelte "[0-9]" and "[a-z]".  Some examples are
380
381           /item[0-9]/;  # matches 'item0' or ... or 'item9'
382           /[0-9bx-z]aa/;  # matches '0aa', ..., '9aa',
383                           # 'baa', 'xaa', 'yaa', or 'zaa'
384           /[0-9a-fA-F]/;  # matches a hexadecimal digit
385           /[0-9a-zA-Z_]/; # matches a "word" character,
386                           # like those in a Perl variable name
387
388       If '-' is the first or last character in a character class, it is
389       treated as an ordinary character; "[-ab]", "[ab-]" and "[a\-b]" are all
390       equivalent.
391
392       The special character '^' in the first position of a character class
393       denotes a negated character class, which matches any character but
394       those in the brackets.  Both "[...]" and "[^...]" must match a
395       character, or the match fails.  Then
396
397           /[^a]at/;  # doesn't match 'aat' or 'at', but matches
398                      # all other 'bat', 'cat, '0at', '%at', etc.
399           /[^0-9]/;  # matches a non-numeric character
400           /[a^]at/;  # matches 'aat' or '^at'; here '^' is ordinary
401
402       Now, even "[0-9]" can be a bother to write multiple times, so in the
403       interest of saving keystrokes and making regexps more readable, Perl
404       has several abbreviations for common character classes, as shown below.
405       Since the introduction of Unicode, unless the "/a" modifier is in
406       effect, these character classes match more than just a few characters
407       in the ASCII range.
408
409       ·   "\d" matches a digit, not just "[0-9]" but also digits from non-
410           roman scripts
411
412       ·   "\s" matches a whitespace character, the set "[\ \t\r\n\f]" and
413           others
414
415       ·   "\w" matches a word character (alphanumeric or '_'), not just
416           "[0-9a-zA-Z_]" but also digits and characters from non-roman
417           scripts
418
419       ·   "\D" is a negated "\d"; it represents any other character than a
420           digit, or "[^\d]"
421
422       ·   "\S" is a negated "\s"; it represents any non-whitespace character
423           "[^\s]"
424
425       ·   "\W" is a negated "\w"; it represents any non-word character
426           "[^\w]"
427
428       ·   The period '.' matches any character but "\n" (unless the modifier
429           "/s" is in effect, as explained below).
430
431       ·   "\N", like the period, matches any character but "\n", but it does
432           so regardless of whether the modifier "/s" is in effect.
433
434       The "/a" modifier, available starting in Perl 5.14,  is used to
435       restrict the matches of "\d", "\s", and "\w" to just those in the ASCII
436       range.  It is useful to keep your program from being needlessly exposed
437       to full Unicode (and its accompanying security considerations) when all
438       you want is to process English-like text.  (The "a" may be doubled,
439       "/aa", to provide even more restrictions, preventing case-insensitive
440       matching of ASCII with non-ASCII characters; otherwise a Unicode
441       "Kelvin Sign" would caselessly match a "k" or "K".)
442
443       The "\d\s\w\D\S\W" abbreviations can be used both inside and outside of
444       bracketed character classes.  Here are some in use:
445
446           /\d\d:\d\d:\d\d/; # matches a hh:mm:ss time format
447           /[\d\s]/;         # matches any digit or whitespace character
448           /\w\W\w/;         # matches a word char, followed by a
449                             # non-word char, followed by a word char
450           /..rt/;           # matches any two chars, followed by 'rt'
451           /end\./;          # matches 'end.'
452           /end[.]/;         # same thing, matches 'end.'
453
454       Because a period is a metacharacter, it needs to be escaped to match as
455       an ordinary period. Because, for example, "\d" and "\w" are sets of
456       characters, it is incorrect to think of "[^\d\w]" as "[\D\W]"; in fact
457       "[^\d\w]" is the same as "[^\w]", which is the same as "[\W]". Think
458       DeMorgan's laws.
459
460       In actuality, the period and "\d\s\w\D\S\W" abbreviations are
461       themselves types of character classes, so the ones surrounded by
462       brackets are just one type of character class.  When we need to make a
463       distinction, we refer to them as "bracketed character classes."
464
465       An anchor useful in basic regexps is the word anchor "\b".  This
466       matches a boundary between a word character and a non-word character
467       "\w\W" or "\W\w":
468
469           $x = "Housecat catenates house and cat";
470           $x =~ /cat/;    # matches cat in 'housecat'
471           $x =~ /\bcat/;  # matches cat in 'catenates'
472           $x =~ /cat\b/;  # matches cat in 'housecat'
473           $x =~ /\bcat\b/;  # matches 'cat' at end of string
474
475       Note in the last example, the end of the string is considered a word
476       boundary.
477
478       For natural language processing (so that, for example, apostrophes are
479       included in words), use instead "\b{wb}"
480
481           "don't" =~ / .+? \b{wb} /x;  # matches the whole string
482
483       You might wonder why '.' matches everything but "\n" - why not every
484       character? The reason is that often one is matching against lines and
485       would like to ignore the newline characters.  For instance, while the
486       string "\n" represents one line, we would like to think of it as empty.
487       Then
488
489           ""   =~ /^$/;    # matches
490           "\n" =~ /^$/;    # matches, $ anchors before "\n"
491
492           ""   =~ /./;      # doesn't match; it needs a char
493           ""   =~ /^.$/;    # doesn't match; it needs a char
494           "\n" =~ /^.$/;    # doesn't match; it needs a char other than "\n"
495           "a"  =~ /^.$/;    # matches
496           "a\n"  =~ /^.$/;  # matches, $ anchors before "\n"
497
498       This behavior is convenient, because we usually want to ignore newlines
499       when we count and match characters in a line.  Sometimes, however, we
500       want to keep track of newlines.  We might even want '^' and '$' to
501       anchor at the beginning and end of lines within the string, rather than
502       just the beginning and end of the string.  Perl allows us to choose
503       between ignoring and paying attention to newlines by using the "/s" and
504       "/m" modifiers.  "/s" and "/m" stand for single line and multi-line and
505       they determine whether a string is to be treated as one continuous
506       string, or as a set of lines.  The two modifiers affect two aspects of
507       how the regexp is interpreted: 1) how the '.' character class is
508       defined, and 2) where the anchors '^' and '$' are able to match.  Here
509       are the four possible combinations:
510
511       ·   no modifiers: Default behavior.  '.' matches any character except
512           "\n".  '^' matches only at the beginning of the string and '$'
513           matches only at the end or before a newline at the end.
514
515       ·   s modifier ("/s"): Treat string as a single long line.  '.' matches
516           any character, even "\n".  '^' matches only at the beginning of the
517           string and '$' matches only at the end or before a newline at the
518           end.
519
520       ·   m modifier ("/m"): Treat string as a set of multiple lines.  '.'
521           matches any character except "\n".  '^' and '$' are able to match
522           at the start or end of any line within the string.
523
524       ·   both s and m modifiers ("/sm"): Treat string as a single long line,
525           but detect multiple lines.  '.' matches any character, even "\n".
526           '^' and '$', however, are able to match at the start or end of any
527           line within the string.
528
529       Here are examples of "/s" and "/m" in action:
530
531           $x = "There once was a girl\nWho programmed in Perl\n";
532
533           $x =~ /^Who/;   # doesn't match, "Who" not at start of string
534           $x =~ /^Who/s;  # doesn't match, "Who" not at start of string
535           $x =~ /^Who/m;  # matches, "Who" at start of second line
536           $x =~ /^Who/sm; # matches, "Who" at start of second line
537
538           $x =~ /girl.Who/;   # doesn't match, "." doesn't match "\n"
539           $x =~ /girl.Who/s;  # matches, "." matches "\n"
540           $x =~ /girl.Who/m;  # doesn't match, "." doesn't match "\n"
541           $x =~ /girl.Who/sm; # matches, "." matches "\n"
542
543       Most of the time, the default behavior is what is wanted, but "/s" and
544       "/m" are occasionally very useful.  If "/m" is being used, the start of
545       the string can still be matched with "\A" and the end of the string can
546       still be matched with the anchors "\Z" (matches both the end and the
547       newline before, like '$'), and "\z" (matches only the end):
548
549           $x =~ /^Who/m;   # matches, "Who" at start of second line
550           $x =~ /\AWho/m;  # doesn't match, "Who" is not at start of string
551
552           $x =~ /girl$/m;  # matches, "girl" at end of first line
553           $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string
554
555           $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
556           $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string
557
558       We now know how to create choices among classes of characters in a
559       regexp.  What about choices among words or character strings? Such
560       choices are described in the next section.
561
562   Matching this or that
563       Sometimes we would like our regexp to be able to match different
564       possible words or character strings.  This is accomplished by using the
565       alternation metacharacter '|'.  To match "dog" or "cat", we form the
566       regexp "dog|cat".  As before, Perl will try to match the regexp at the
567       earliest possible point in the string.  At each character position,
568       Perl will first try to match the first alternative, "dog".  If "dog"
569       doesn't match, Perl will then try the next alternative, "cat".  If
570       "cat" doesn't match either, then the match fails and Perl moves to the
571       next position in the string.  Some examples:
572
573           "cats and dogs" =~ /cat|dog|bird/;  # matches "cat"
574           "cats and dogs" =~ /dog|cat|bird/;  # matches "cat"
575
576       Even though "dog" is the first alternative in the second regexp, "cat"
577       is able to match earlier in the string.
578
579           "cats"          =~ /c|ca|cat|cats/; # matches "c"
580           "cats"          =~ /cats|cat|ca|c/; # matches "cats"
581
582       Here, all the alternatives match at the first string position, so the
583       first alternative is the one that matches.  If some of the alternatives
584       are truncations of the others, put the longest ones first to give them
585       a chance to match.
586
587           "cab" =~ /a|b|c/ # matches "c"
588                            # /a|b|c/ == /[abc]/
589
590       The last example points out that character classes are like
591       alternations of characters.  At a given character position, the first
592       alternative that allows the regexp match to succeed will be the one
593       that matches.
594
595   Grouping things and hierarchical matching
596       Alternation allows a regexp to choose among alternatives, but by itself
597       it is unsatisfying.  The reason is that each alternative is a whole
598       regexp, but sometime we want alternatives for just part of a regexp.
599       For instance, suppose we want to search for housecats or housekeepers.
600       The regexp "housecat|housekeeper" fits the bill, but is inefficient
601       because we had to type "house" twice.  It would be nice to have parts
602       of the regexp be constant, like "house", and some parts have
603       alternatives, like "cat|keeper".
604
605       The grouping metacharacters "()" solve this problem.  Grouping allows
606       parts of a regexp to be treated as a single unit.  Parts of a regexp
607       are grouped by enclosing them in parentheses.  Thus we could solve the
608       "housecat|housekeeper" by forming the regexp as "house(cat|keeper)".
609       The regexp "house(cat|keeper)" means match "house" followed by either
610       "cat" or "keeper".  Some more examples are
611
612           /(a|b)b/;    # matches 'ab' or 'bb'
613           /(ac|b)b/;   # matches 'acb' or 'bb'
614           /(^a|b)c/;   # matches 'ac' at start of string or 'bc' anywhere
615           /(a|[bc])d/; # matches 'ad', 'bd', or 'cd'
616
617           /house(cat|)/;  # matches either 'housecat' or 'house'
618           /house(cat(s|)|)/;  # matches either 'housecats' or 'housecat' or
619                               # 'house'.  Note groups can be nested.
620
621           /(19|20|)\d\d/;  # match years 19xx, 20xx, or the Y2K problem, xx
622           "20" =~ /(19|20|)\d\d/;  # matches the null alternative '()\d\d',
623                                    # because '20\d\d' can't match
624
625       Alternations behave the same way in groups as out of them: at a given
626       string position, the leftmost alternative that allows the regexp to
627       match is taken.  So in the last example at the first string position,
628       "20" matches the second alternative, but there is nothing left over to
629       match the next two digits "\d\d".  So Perl moves on to the next
630       alternative, which is the null alternative and that works, since "20"
631       is two digits.
632
633       The process of trying one alternative, seeing if it matches, and moving
634       on to the next alternative, while going back in the string from where
635       the previous alternative was tried, if it doesn't, is called
636       backtracking.  The term "backtracking" comes from the idea that
637       matching a regexp is like a walk in the woods.  Successfully matching a
638       regexp is like arriving at a destination.  There are many possible
639       trailheads, one for each string position, and each one is tried in
640       order, left to right.  From each trailhead there may be many paths,
641       some of which get you there, and some which are dead ends.  When you
642       walk along a trail and hit a dead end, you have to backtrack along the
643       trail to an earlier point to try another trail.  If you hit your
644       destination, you stop immediately and forget about trying all the other
645       trails.  You are persistent, and only if you have tried all the trails
646       from all the trailheads and not arrived at your destination, do you
647       declare failure.  To be concrete, here is a step-by-step analysis of
648       what Perl does when it tries to match the regexp
649
650           "abcde" =~ /(abd|abc)(df|d|de)/;
651
652       0. Start with the first letter in the string 'a'.
653
654
655       1. Try the first alternative in the first group 'abd'.
656
657
658       2.  Match 'a' followed by 'b'. So far so good.
659
660
661       3.  'd' in the regexp doesn't match 'c' in the string - a dead end.  So
662       backtrack two characters and pick the second alternative in the first
663       group 'abc'.
664
665
666       4.  Match 'a' followed by 'b' followed by 'c'.  We are on a roll and
667       have satisfied the first group. Set $1 to 'abc'.
668
669
670       5 Move on to the second group and pick the first alternative 'df'.
671
672
673       6 Match the 'd'.
674
675
676       7.  'f' in the regexp doesn't match 'e' in the string, so a dead end.
677       Backtrack one character and pick the second alternative in the second
678       group 'd'.
679
680
681       8.  'd' matches. The second grouping is satisfied, so set $2 to 'd'.
682
683
684       9.  We are at the end of the regexp, so we are done! We have matched
685       'abcd' out of the string "abcde".
686
687       There are a couple of things to note about this analysis.  First, the
688       third alternative in the second group 'de' also allows a match, but we
689       stopped before we got to it - at a given character position, leftmost
690       wins.  Second, we were able to get a match at the first character
691       position of the string 'a'.  If there were no matches at the first
692       position, Perl would move to the second character position 'b' and
693       attempt the match all over again.  Only when all possible paths at all
694       possible character positions have been exhausted does Perl give up and
695       declare "$string =~ /(abd|abc)(df|d|de)/;" to be false.
696
697       Even with all this work, regexp matching happens remarkably fast.  To
698       speed things up, Perl compiles the regexp into a compact sequence of
699       opcodes that can often fit inside a processor cache.  When the code is
700       executed, these opcodes can then run at full throttle and search very
701       quickly.
702
703   Extracting matches
704       The grouping metacharacters "()" also serve another completely
705       different function: they allow the extraction of the parts of a string
706       that matched.  This is very useful to find out what matched and for
707       text processing in general.  For each grouping, the part that matched
708       inside goes into the special variables $1, $2, etc.  They can be used
709       just as ordinary variables:
710
711           # extract hours, minutes, seconds
712           if ($time =~ /(\d\d):(\d\d):(\d\d)/) {    # match hh:mm:ss format
713               $hours = $1;
714               $minutes = $2;
715               $seconds = $3;
716           }
717
718       Now, we know that in scalar context, "$time =~ /(\d\d):(\d\d):(\d\d)/"
719       returns a true or false value.  In list context, however, it returns
720       the list of matched values "($1,$2,$3)".  So we could write the code
721       more compactly as
722
723           # extract hours, minutes, seconds
724           ($hours, $minutes, $second) = ($time =~ /(\d\d):(\d\d):(\d\d)/);
725
726       If the groupings in a regexp are nested, $1 gets the group with the
727       leftmost opening parenthesis, $2 the next opening parenthesis, etc.
728       Here is a regexp with nested groups:
729
730           /(ab(cd|ef)((gi)|j))/;
731            1  2      34
732
733       If this regexp matches, $1 contains a string starting with 'ab', $2 is
734       either set to 'cd' or 'ef', $3 equals either 'gi' or 'j', and $4 is
735       either set to 'gi', just like $3, or it remains undefined.
736
737       For convenience, Perl sets $+ to the string held by the highest
738       numbered $1, $2,... that got assigned (and, somewhat related, $^N to
739       the value of the $1, $2,... most-recently assigned; i.e. the $1, $2,...
740       associated with the rightmost closing parenthesis used in the match).
741
742   Backreferences
743       Closely associated with the matching variables $1, $2, ... are the
744       backreferences "\g1", "\g2",...  Backreferences are simply matching
745       variables that can be used inside a regexp.  This is a really nice
746       feature; what matches later in a regexp is made to depend on what
747       matched earlier in the regexp.  Suppose we wanted to look for doubled
748       words in a text, like "the the".  The following regexp finds all
749       3-letter doubles with a space in between:
750
751           /\b(\w\w\w)\s\g1\b/;
752
753       The grouping assigns a value to "\g1", so that the same 3-letter
754       sequence is used for both parts.
755
756       A similar task is to find words consisting of two identical parts:
757
758           % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\g1$' /usr/dict/words
759           beriberi
760           booboo
761           coco
762           mama
763           murmur
764           papa
765
766       The regexp has a single grouping which considers 4-letter combinations,
767       then 3-letter combinations, etc., and uses "\g1" to look for a repeat.
768       Although $1 and "\g1" represent the same thing, care should be taken to
769       use matched variables $1, $2,... only outside a regexp and
770       backreferences "\g1", "\g2",... only inside a regexp; not doing so may
771       lead to surprising and unsatisfactory results.
772
773   Relative backreferences
774       Counting the opening parentheses to get the correct number for a
775       backreference is error-prone as soon as there is more than one
776       capturing group.  A more convenient technique became available with
777       Perl 5.10: relative backreferences. To refer to the immediately
778       preceding capture group one now may write "\g{-1}", the next but last
779       is available via "\g{-2}", and so on.
780
781       Another good reason in addition to readability and maintainability for
782       using relative backreferences is illustrated by the following example,
783       where a simple pattern for matching peculiar strings is used:
784
785           $a99a = '([a-z])(\d)\g2\g1';   # matches a11a, g22g, x33x, etc.
786
787       Now that we have this pattern stored as a handy string, we might feel
788       tempted to use it as a part of some other pattern:
789
790           $line = "code=e99e";
791           if ($line =~ /^(\w+)=$a99a$/){   # unexpected behavior!
792               print "$1 is valid\n";
793           } else {
794               print "bad line: '$line'\n";
795           }
796
797       But this doesn't match, at least not the way one might expect. Only
798       after inserting the interpolated $a99a and looking at the resulting
799       full text of the regexp is it obvious that the backreferences have
800       backfired. The subexpression "(\w+)" has snatched number 1 and demoted
801       the groups in $a99a by one rank. This can be avoided by using relative
802       backreferences:
803
804           $a99a = '([a-z])(\d)\g{-1}\g{-2}';  # safe for being interpolated
805
806   Named backreferences
807       Perl 5.10 also introduced named capture groups and named
808       backreferences.  To attach a name to a capturing group, you write
809       either "(?<name>...)" or "(?'name'...)".  The backreference may then be
810       written as "\g{name}".  It is permissible to attach the same name to
811       more than one group, but then only the leftmost one of the eponymous
812       set can be referenced.  Outside of the pattern a named capture group is
813       accessible through the "%+" hash.
814
815       Assuming that we have to match calendar dates which may be given in one
816       of the three formats yyyy-mm-dd, mm/dd/yyyy or dd.mm.yyyy, we can write
817       three suitable patterns where we use 'd', 'm' and 'y' respectively as
818       the names of the groups capturing the pertaining components of a date.
819       The matching operation combines the three patterns as alternatives:
820
821           $fmt1 = '(?<y>\d\d\d\d)-(?<m>\d\d)-(?<d>\d\d)';
822           $fmt2 = '(?<m>\d\d)/(?<d>\d\d)/(?<y>\d\d\d\d)';
823           $fmt3 = '(?<d>\d\d)\.(?<m>\d\d)\.(?<y>\d\d\d\d)';
824           for my $d (qw(2006-10-21 15.01.2007 10/31/2005)) {
825               if ( $d =~ m{$fmt1|$fmt2|$fmt3} ){
826                   print "day=$+{d} month=$+{m} year=$+{y}\n";
827               }
828           }
829
830       If any of the alternatives matches, the hash "%+" is bound to contain
831       the three key-value pairs.
832
833   Alternative capture group numbering
834       Yet another capturing group numbering technique (also as from Perl
835       5.10) deals with the problem of referring to groups within a set of
836       alternatives.  Consider a pattern for matching a time of the day, civil
837       or military style:
838
839           if ( $time =~ /(\d\d|\d):(\d\d)|(\d\d)(\d\d)/ ){
840               # process hour and minute
841           }
842
843       Processing the results requires an additional if statement to determine
844       whether $1 and $2 or $3 and $4 contain the goodies. It would be easier
845       if we could use group numbers 1 and 2 in second alternative as well,
846       and this is exactly what the parenthesized construct "(?|...)", set
847       around an alternative achieves. Here is an extended version of the
848       previous pattern:
849
850         if($time =~ /(?|(\d\d|\d):(\d\d)|(\d\d)(\d\d))\s+([A-Z][A-Z][A-Z])/){
851             print "hour=$1 minute=$2 zone=$3\n";
852         }
853
854       Within the alternative numbering group, group numbers start at the same
855       position for each alternative. After the group, numbering continues
856       with one higher than the maximum reached across all the alternatives.
857
858   Position information
859       In addition to what was matched, Perl also provides the positions of
860       what was matched as contents of the "@-" and "@+" arrays. "$-[0]" is
861       the position of the start of the entire match and $+[0] is the position
862       of the end. Similarly, "$-[n]" is the position of the start of the $n
863       match and $+[n] is the position of the end. If $n is undefined, so are
864       "$-[n]" and $+[n]. Then this code
865
866           $x = "Mmm...donut, thought Homer";
867           $x =~ /^(Mmm|Yech)\.\.\.(donut|peas)/; # matches
868           foreach $exp (1..$#-) {
869               print "Match $exp: '${$exp}' at position ($-[$exp],$+[$exp])\n";
870           }
871
872       prints
873
874           Match 1: 'Mmm' at position (0,3)
875           Match 2: 'donut' at position (6,11)
876
877       Even if there are no groupings in a regexp, it is still possible to
878       find out what exactly matched in a string.  If you use them, Perl will
879       set "$`" to the part of the string before the match, will set $& to the
880       part of the string that matched, and will set '$' to the part of the
881       string after the match.  An example:
882
883           $x = "the cat caught the mouse";
884           $x =~ /cat/;  # $` = 'the ', $& = 'cat', $' = ' caught the mouse'
885           $x =~ /the/;  # $` = '', $& = 'the', $' = ' cat caught the mouse'
886
887       In the second match, "$`" equals '' because the regexp matched at the
888       first character position in the string and stopped; it never saw the
889       second "the".
890
891       If your code is to run on Perl versions earlier than 5.20, it is
892       worthwhile to note that using "$`" and '$' slows down regexp matching
893       quite a bit, while $& slows it down to a lesser extent, because if they
894       are used in one regexp in a program, they are generated for all regexps
895       in the program.  So if raw performance is a goal of your application,
896       they should be avoided.  If you need to extract the corresponding
897       substrings, use "@-" and "@+" instead:
898
899           $` is the same as substr( $x, 0, $-[0] )
900           $& is the same as substr( $x, $-[0], $+[0]-$-[0] )
901           $' is the same as substr( $x, $+[0] )
902
903       As of Perl 5.10, the "${^PREMATCH}", "${^MATCH}" and "${^POSTMATCH}"
904       variables may be used.  These are only set if the "/p" modifier is
905       present.  Consequently they do not penalize the rest of the program.
906       In Perl 5.20, "${^PREMATCH}", "${^MATCH}" and "${^POSTMATCH}" are
907       available whether the "/p" has been used or not (the modifier is
908       ignored), and "$`", '$' and $& do not cause any speed difference.
909
910   Non-capturing groupings
911       A group that is required to bundle a set of alternatives may or may not
912       be useful as a capturing group.  If it isn't, it just creates a
913       superfluous addition to the set of available capture group values,
914       inside as well as outside the regexp.  Non-capturing groupings, denoted
915       by "(?:regexp)", still allow the regexp to be treated as a single unit,
916       but don't establish a capturing group at the same time.  Both capturing
917       and non-capturing groupings are allowed to co-exist in the same regexp.
918       Because there is no extraction, non-capturing groupings are faster than
919       capturing groupings.  Non-capturing groupings are also handy for
920       choosing exactly which parts of a regexp are to be extracted to
921       matching variables:
922
923           # match a number, $1-$4 are set, but we only want $1
924           /([+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)/;
925
926           # match a number faster , only $1 is set
927           /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)/;
928
929           # match a number, get $1 = whole number, $2 = exponent
930           /([+-]?\ *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?)/;
931
932       Non-capturing groupings are also useful for removing nuisance elements
933       gathered from a split operation where parentheses are required for some
934       reason:
935
936           $x = '12aba34ba5';
937           @num = split /(a|b)+/, $x;    # @num = ('12','a','34','a','5')
938           @num = split /(?:a|b)+/, $x;  # @num = ('12','34','5')
939
940       In Perl 5.22 and later, all groups within a regexp can be set to non-
941       capturing by using the new "/n" flag:
942
943           "hello" =~ /(hi|hello)/n; # $1 is not set!
944
945       See "n" in perlre for more information.
946
947   Matching repetitions
948       The examples in the previous section display an annoying weakness.  We
949       were only matching 3-letter words, or chunks of words of 4 letters or
950       less.  We'd like to be able to match words or, more generally, strings
951       of any length, without writing out tedious alternatives like
952       "\w\w\w\w|\w\w\w|\w\w|\w".
953
954       This is exactly the problem the quantifier metacharacters '?', '*',
955       '+', and "{}" were created for.  They allow us to delimit the number of
956       repeats for a portion of a regexp we consider to be a match.
957       Quantifiers are put immediately after the character, character class,
958       or grouping that we want to specify.  They have the following meanings:
959
960       ·   "a?" means: match 'a' 1 or 0 times
961
962       ·   "a*" means: match 'a' 0 or more times, i.e., any number of times
963
964       ·   "a+" means: match 'a' 1 or more times, i.e., at least once
965
966       ·   "a{n,m}" means: match at least "n" times, but not more than "m"
967           times.
968
969       ·   "a{n,}" means: match at least "n" or more times
970
971       ·   "a{n}" means: match exactly "n" times
972
973       Here are some examples:
974
975           /[a-z]+\s+\d*/;  # match a lowercase word, at least one space, and
976                            # any number of digits
977           /(\w+)\s+\g1/;    # match doubled words of arbitrary length
978           /y(es)?/i;       # matches 'y', 'Y', or a case-insensitive 'yes'
979           $year =~ /^\d{2,4}$/;  # make sure year is at least 2 but not more
980                                  # than 4 digits
981           $year =~ /^\d{4}$|^\d{2}$/; # better match; throw out 3-digit dates
982           $year =~ /^\d{2}(\d{2})?$/; # same thing written differently.
983                                       # However, this captures the last two
984                                       # digits in $1 and the other does not.
985
986           % simple_grep '^(\w+)\g1$' /usr/dict/words   # isn't this easier?
987           beriberi
988           booboo
989           coco
990           mama
991           murmur
992           papa
993
994       For all of these quantifiers, Perl will try to match as much of the
995       string as possible, while still allowing the regexp to succeed.  Thus
996       with "/a?.../", Perl will first try to match the regexp with the 'a'
997       present; if that fails, Perl will try to match the regexp without the
998       'a' present.  For the quantifier '*', we get the following:
999
1000           $x = "the cat in the hat";
1001           $x =~ /^(.*)(cat)(.*)$/; # matches,
1002                                    # $1 = 'the '
1003                                    # $2 = 'cat'
1004                                    # $3 = ' in the hat'
1005
1006       Which is what we might expect, the match finds the only "cat" in the
1007       string and locks onto it.  Consider, however, this regexp:
1008
1009           $x =~ /^(.*)(at)(.*)$/; # matches,
1010                                   # $1 = 'the cat in the h'
1011                                   # $2 = 'at'
1012                                   # $3 = ''   (0 characters match)
1013
1014       One might initially guess that Perl would find the "at" in "cat" and
1015       stop there, but that wouldn't give the longest possible string to the
1016       first quantifier ".*".  Instead, the first quantifier ".*" grabs as
1017       much of the string as possible while still having the regexp match.  In
1018       this example, that means having the "at" sequence with the final "at"
1019       in the string.  The other important principle illustrated here is that,
1020       when there are two or more elements in a regexp, the leftmost
1021       quantifier, if there is one, gets to grab as much of the string as
1022       possible, leaving the rest of the regexp to fight over scraps.  Thus in
1023       our example, the first quantifier ".*" grabs most of the string, while
1024       the second quantifier ".*" gets the empty string.   Quantifiers that
1025       grab as much of the string as possible are called maximal match or
1026       greedy quantifiers.
1027
1028       When a regexp can match a string in several different ways, we can use
1029       the principles above to predict which way the regexp will match:
1030
1031       ·   Principle 0: Taken as a whole, any regexp will be matched at the
1032           earliest possible position in the string.
1033
1034       ·   Principle 1: In an alternation "a|b|c...", the leftmost alternative
1035           that allows a match for the whole regexp will be the one used.
1036
1037       ·   Principle 2: The maximal matching quantifiers '?', '*', '+' and
1038           "{n,m}" will in general match as much of the string as possible
1039           while still allowing the whole regexp to match.
1040
1041       ·   Principle 3: If there are two or more elements in a regexp, the
1042           leftmost greedy quantifier, if any, will match as much of the
1043           string as possible while still allowing the whole regexp to match.
1044           The next leftmost greedy quantifier, if any, will try to match as
1045           much of the string remaining available to it as possible, while
1046           still allowing the whole regexp to match.  And so on, until all the
1047           regexp elements are satisfied.
1048
1049       As we have seen above, Principle 0 overrides the others. The regexp
1050       will be matched as early as possible, with the other principles
1051       determining how the regexp matches at that earliest character position.
1052
1053       Here is an example of these principles in action:
1054
1055           $x = "The programming republic of Perl";
1056           $x =~ /^(.+)(e|r)(.*)$/;  # matches,
1057                                     # $1 = 'The programming republic of Pe'
1058                                     # $2 = 'r'
1059                                     # $3 = 'l'
1060
1061       This regexp matches at the earliest string position, 'T'.  One might
1062       think that 'e', being leftmost in the alternation, would be matched,
1063       but 'r' produces the longest string in the first quantifier.
1064
1065           $x =~ /(m{1,2})(.*)$/;  # matches,
1066                                   # $1 = 'mm'
1067                                   # $2 = 'ing republic of Perl'
1068
1069       Here, The earliest possible match is at the first 'm' in "programming".
1070       "m{1,2}" is the first quantifier, so it gets to match a maximal "mm".
1071
1072           $x =~ /.*(m{1,2})(.*)$/;  # matches,
1073                                     # $1 = 'm'
1074                                     # $2 = 'ing republic of Perl'
1075
1076       Here, the regexp matches at the start of the string. The first
1077       quantifier ".*" grabs as much as possible, leaving just a single 'm'
1078       for the second quantifier "m{1,2}".
1079
1080           $x =~ /(.?)(m{1,2})(.*)$/;  # matches,
1081                                       # $1 = 'a'
1082                                       # $2 = 'mm'
1083                                       # $3 = 'ing republic of Perl'
1084
1085       Here, ".?" eats its maximal one character at the earliest possible
1086       position in the string, 'a' in "programming", leaving "m{1,2}" the
1087       opportunity to match both 'm''s. Finally,
1088
1089           "aXXXb" =~ /(X*)/; # matches with $1 = ''
1090
1091       because it can match zero copies of 'X' at the beginning of the string.
1092       If you definitely want to match at least one 'X', use "X+", not "X*".
1093
1094       Sometimes greed is not good.  At times, we would like quantifiers to
1095       match a minimal piece of string, rather than a maximal piece.  For this
1096       purpose, Larry Wall created the minimal match or non-greedy quantifiers
1097       "??", "*?", "+?", and "{}?".  These are the usual quantifiers with a
1098       '?' appended to them.  They have the following meanings:
1099
1100       ·   "a??" means: match 'a' 0 or 1 times. Try 0 first, then 1.
1101
1102       ·   "a*?" means: match 'a' 0 or more times, i.e., any number of times,
1103           but as few times as possible
1104
1105       ·   "a+?" means: match 'a' 1 or more times, i.e., at least once, but as
1106           few times as possible
1107
1108       ·   "a{n,m}?" means: match at least "n" times, not more than "m" times,
1109           as few times as possible
1110
1111       ·   "a{n,}?" means: match at least "n" times, but as few times as
1112           possible
1113
1114       ·   "a{n}?" means: match exactly "n" times.  Because we match exactly
1115           "n" times, "a{n}?" is equivalent to "a{n}" and is just there for
1116           notational consistency.
1117
1118       Let's look at the example above, but with minimal quantifiers:
1119
1120           $x = "The programming republic of Perl";
1121           $x =~ /^(.+?)(e|r)(.*)$/; # matches,
1122                                     # $1 = 'Th'
1123                                     # $2 = 'e'
1124                                     # $3 = ' programming republic of Perl'
1125
1126       The minimal string that will allow both the start of the string '^' and
1127       the alternation to match is "Th", with the alternation "e|r" matching
1128       'e'.  The second quantifier ".*" is free to gobble up the rest of the
1129       string.
1130
1131           $x =~ /(m{1,2}?)(.*?)$/;  # matches,
1132                                     # $1 = 'm'
1133                                     # $2 = 'ming republic of Perl'
1134
1135       The first string position that this regexp can match is at the first
1136       'm' in "programming". At this position, the minimal "m{1,2}?"  matches
1137       just one 'm'.  Although the second quantifier ".*?" would prefer to
1138       match no characters, it is constrained by the end-of-string anchor '$'
1139       to match the rest of the string.
1140
1141           $x =~ /(.*?)(m{1,2}?)(.*)$/;  # matches,
1142                                         # $1 = 'The progra'
1143                                         # $2 = 'm'
1144                                         # $3 = 'ming republic of Perl'
1145
1146       In this regexp, you might expect the first minimal quantifier ".*?"  to
1147       match the empty string, because it is not constrained by a '^' anchor
1148       to match the beginning of the word.  Principle 0 applies here, however.
1149       Because it is possible for the whole regexp to match at the start of
1150       the string, it will match at the start of the string.  Thus the first
1151       quantifier has to match everything up to the first 'm'.  The second
1152       minimal quantifier matches just one 'm' and the third quantifier
1153       matches the rest of the string.
1154
1155           $x =~ /(.??)(m{1,2})(.*)$/;  # matches,
1156                                        # $1 = 'a'
1157                                        # $2 = 'mm'
1158                                        # $3 = 'ing republic of Perl'
1159
1160       Just as in the previous regexp, the first quantifier ".??" can match
1161       earliest at position 'a', so it does.  The second quantifier is greedy,
1162       so it matches "mm", and the third matches the rest of the string.
1163
1164       We can modify principle 3 above to take into account non-greedy
1165       quantifiers:
1166
1167       ·   Principle 3: If there are two or more elements in a regexp, the
1168           leftmost greedy (non-greedy) quantifier, if any, will match as much
1169           (little) of the string as possible while still allowing the whole
1170           regexp to match.  The next leftmost greedy (non-greedy) quantifier,
1171           if any, will try to match as much (little) of the string remaining
1172           available to it as possible, while still allowing the whole regexp
1173           to match.  And so on, until all the regexp elements are satisfied.
1174
1175       Just like alternation, quantifiers are also susceptible to
1176       backtracking.  Here is a step-by-step analysis of the example
1177
1178           $x = "the cat in the hat";
1179           $x =~ /^(.*)(at)(.*)$/; # matches,
1180                                   # $1 = 'the cat in the h'
1181                                   # $2 = 'at'
1182                                   # $3 = ''   (0 matches)
1183
1184       0.  Start with the first letter in the string 't'.
1185
1186
1187       1.  The first quantifier '.*' starts out by matching the whole string
1188       ""the cat in the hat"".
1189
1190
1191       2.  'a' in the regexp element 'at' doesn't match the end of the string.
1192       Backtrack one character.
1193
1194
1195       3.  'a' in the regexp element 'at' still doesn't match the last letter
1196       of the string 't', so backtrack one more character.
1197
1198
1199       4.  Now we can match the 'a' and the 't'.
1200
1201
1202       5.  Move on to the third element '.*'.  Since we are at the end of the
1203       string and '.*' can match 0 times, assign it the empty string.
1204
1205
1206       6.  We are done!
1207
1208       Most of the time, all this moving forward and backtracking happens
1209       quickly and searching is fast. There are some pathological regexps,
1210       however, whose execution time exponentially grows with the size of the
1211       string.  A typical structure that blows up in your face is of the form
1212
1213           /(a|b+)*/;
1214
1215       The problem is the nested indeterminate quantifiers.  There are many
1216       different ways of partitioning a string of length n between the '+' and
1217       '*': one repetition with "b+" of length n, two repetitions with the
1218       first "b+" length k and the second with length n-k, m repetitions whose
1219       bits add up to length n, etc.  In fact there are an exponential number
1220       of ways to partition a string as a function of its length.  A regexp
1221       may get lucky and match early in the process, but if there is no match,
1222       Perl will try every possibility before giving up.  So be careful with
1223       nested '*''s, "{n,m}"'s, and '+''s.  The book Mastering Regular
1224       Expressions by Jeffrey Friedl gives a wonderful discussion of this and
1225       other efficiency issues.
1226
1227   Possessive quantifiers
1228       Backtracking during the relentless search for a match may be a waste of
1229       time, particularly when the match is bound to fail.  Consider the
1230       simple pattern
1231
1232           /^\w+\s+\w+$/; # a word, spaces, a word
1233
1234       Whenever this is applied to a string which doesn't quite meet the
1235       pattern's expectations such as "abc  " or "abc  def ", the regexp
1236       engine will backtrack, approximately once for each character in the
1237       string.  But we know that there is no way around taking all of the
1238       initial word characters to match the first repetition, that all spaces
1239       must be eaten by the middle part, and the same goes for the second
1240       word.
1241
1242       With the introduction of the possessive quantifiers in Perl 5.10, we
1243       have a way of instructing the regexp engine not to backtrack, with the
1244       usual quantifiers with a '+' appended to them.  This makes them greedy
1245       as well as stingy; once they succeed they won't give anything back to
1246       permit another solution. They have the following meanings:
1247
1248       ·   "a{n,m}+" means: match at least "n" times, not more than "m" times,
1249           as many times as possible, and don't give anything up. "a?+" is
1250           short for "a{0,1}+"
1251
1252       ·   "a{n,}+" means: match at least "n" times, but as many times as
1253           possible, and don't give anything up. "a*+" is short for "a{0,}+"
1254           and "a++" is short for "a{1,}+".
1255
1256       ·   "a{n}+" means: match exactly "n" times.  It is just there for
1257           notational consistency.
1258
1259       These possessive quantifiers represent a special case of a more general
1260       concept, the independent subexpression, see below.
1261
1262       As an example where a possessive quantifier is suitable we consider
1263       matching a quoted string, as it appears in several programming
1264       languages.  The backslash is used as an escape character that indicates
1265       that the next character is to be taken literally, as another character
1266       for the string.  Therefore, after the opening quote, we expect a
1267       (possibly empty) sequence of alternatives: either some character except
1268       an unescaped quote or backslash or an escaped character.
1269
1270           /"(?:[^"\\]++|\\.)*+"/;
1271
1272   Building a regexp
1273       At this point, we have all the basic regexp concepts covered, so let's
1274       give a more involved example of a regular expression.  We will build a
1275       regexp that matches numbers.
1276
1277       The first task in building a regexp is to decide what we want to match
1278       and what we want to exclude.  In our case, we want to match both
1279       integers and floating point numbers and we want to reject any string
1280       that isn't a number.
1281
1282       The next task is to break the problem down into smaller problems that
1283       are easily converted into a regexp.
1284
1285       The simplest case is integers.  These consist of a sequence of digits,
1286       with an optional sign in front.  The digits we can represent with "\d+"
1287       and the sign can be matched with "[+-]".  Thus the integer regexp is
1288
1289           /[+-]?\d+/;  # matches integers
1290
1291       A floating point number potentially has a sign, an integral part, a
1292       decimal point, a fractional part, and an exponent.  One or more of
1293       these parts is optional, so we need to check out the different
1294       possibilities.  Floating point numbers which are in proper form include
1295       123., 0.345, .34, -1e6, and 25.4E-72.  As with integers, the sign out
1296       front is completely optional and can be matched by "[+-]?".  We can see
1297       that if there is no exponent, floating point numbers must have a
1298       decimal point, otherwise they are integers.  We might be tempted to
1299       model these with "\d*\.\d*", but this would also match just a single
1300       decimal point, which is not a number.  So the three cases of floating
1301       point number without exponent are
1302
1303          /[+-]?\d+\./;  # 1., 321., etc.
1304          /[+-]?\.\d+/;  # .1, .234, etc.
1305          /[+-]?\d+\.\d+/;  # 1.0, 30.56, etc.
1306
1307       These can be combined into a single regexp with a three-way
1308       alternation:
1309
1310          /[+-]?(\d+\.\d+|\d+\.|\.\d+)/;  # floating point, no exponent
1311
1312       In this alternation, it is important to put '\d+\.\d+' before '\d+\.'.
1313       If '\d+\.' were first, the regexp would happily match that and ignore
1314       the fractional part of the number.
1315
1316       Now consider floating point numbers with exponents.  The key
1317       observation here is that both integers and numbers with decimal points
1318       are allowed in front of an exponent.  Then exponents, like the overall
1319       sign, are independent of whether we are matching numbers with or
1320       without decimal points, and can be "decoupled" from the mantissa.  The
1321       overall form of the regexp now becomes clear:
1322
1323           /^(optional sign)(integer | f.p. mantissa)(optional exponent)$/;
1324
1325       The exponent is an 'e' or 'E', followed by an integer.  So the exponent
1326       regexp is
1327
1328          /[eE][+-]?\d+/;  # exponent
1329
1330       Putting all the parts together, we get a regexp that matches numbers:
1331
1332          /^[+-]?(\d+\.\d+|\d+\.|\.\d+|\d+)([eE][+-]?\d+)?$/;  # Ta da!
1333
1334       Long regexps like this may impress your friends, but can be hard to
1335       decipher.  In complex situations like this, the "/x" modifier for a
1336       match is invaluable.  It allows one to put nearly arbitrary whitespace
1337       and comments into a regexp without affecting their meaning.  Using it,
1338       we can rewrite our "extended" regexp in the more pleasing form
1339
1340          /^
1341             [+-]?         # first, match an optional sign
1342             (             # then match integers or f.p. mantissas:
1343                 \d+\.\d+  # mantissa of the form a.b
1344                |\d+\.     # mantissa of the form a.
1345                |\.\d+     # mantissa of the form .b
1346                |\d+       # integer of the form a
1347             )
1348             ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
1349          $/x;
1350
1351       If whitespace is mostly irrelevant, how does one include space
1352       characters in an extended regexp? The answer is to backslash it '\ ' or
1353       put it in a character class "[ ]".  The same thing goes for pound
1354       signs: use "\#" or "[#]".  For instance, Perl allows a space between
1355       the sign and the mantissa or integer, and we could add this to our
1356       regexp as follows:
1357
1358          /^
1359             [+-]?\ *      # first, match an optional sign *and space*
1360             (             # then match integers or f.p. mantissas:
1361                 \d+\.\d+  # mantissa of the form a.b
1362                |\d+\.     # mantissa of the form a.
1363                |\.\d+     # mantissa of the form .b
1364                |\d+       # integer of the form a
1365             )
1366             ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
1367          $/x;
1368
1369       In this form, it is easier to see a way to simplify the alternation.
1370       Alternatives 1, 2, and 4 all start with "\d+", so it could be factored
1371       out:
1372
1373          /^
1374             [+-]?\ *      # first, match an optional sign
1375             (             # then match integers or f.p. mantissas:
1376                 \d+       # start out with a ...
1377                 (
1378                     \.\d* # mantissa of the form a.b or a.
1379                 )?        # ? takes care of integers of the form a
1380                |\.\d+     # mantissa of the form .b
1381             )
1382             ( [eE] [+-]? \d+ )?  # finally, optionally match an exponent
1383          $/x;
1384
1385       Starting in Perl v5.26, specifying "/xx" changes the square-bracketed
1386       portions of a pattern to ignore tabs and space characters unless they
1387       are escaped by preceding them with a backslash.  So, we could write
1388
1389          /^
1390             [ + - ]?\ *   # first, match an optional sign
1391             (             # then match integers or f.p. mantissas:
1392                 \d+       # start out with a ...
1393                 (
1394                     \.\d* # mantissa of the form a.b or a.
1395                 )?        # ? takes care of integers of the form a
1396                |\.\d+     # mantissa of the form .b
1397             )
1398             ( [ e E ] [ + - ]? \d+ )?  # finally, optionally match an exponent
1399          $/xx;
1400
1401       This doesn't really improve the legibility of this example, but it's
1402       available in case you want it.  Squashing the pattern down to the
1403       compact form, we have
1404
1405           /^[+-]?\ *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/;
1406
1407       This is our final regexp.  To recap, we built a regexp by
1408
1409       ·   specifying the task in detail,
1410
1411       ·   breaking down the problem into smaller parts,
1412
1413       ·   translating the small parts into regexps,
1414
1415       ·   combining the regexps,
1416
1417       ·   and optimizing the final combined regexp.
1418
1419       These are also the typical steps involved in writing a computer
1420       program.  This makes perfect sense, because regular expressions are
1421       essentially programs written in a little computer language that
1422       specifies patterns.
1423
1424   Using regular expressions in Perl
1425       The last topic of Part 1 briefly covers how regexps are used in Perl
1426       programs.  Where do they fit into Perl syntax?
1427
1428       We have already introduced the matching operator in its default
1429       "/regexp/" and arbitrary delimiter "m!regexp!" forms.  We have used the
1430       binding operator "=~" and its negation "!~" to test for string matches.
1431       Associated with the matching operator, we have discussed the single
1432       line "/s", multi-line "/m", case-insensitive "/i" and extended "/x"
1433       modifiers.  There are a few more things you might want to know about
1434       matching operators.
1435
1436       Prohibiting substitution
1437
1438       If you change $pattern after the first substitution happens, Perl will
1439       ignore it.  If you don't want any substitutions at all, use the special
1440       delimiter "m''":
1441
1442           @pattern = ('Seuss');
1443           while (<>) {
1444               print if m'@pattern';  # matches literal '@pattern', not 'Seuss'
1445           }
1446
1447       Similar to strings, "m''" acts like apostrophes on a regexp; all other
1448       'm' delimiters act like quotes.  If the regexp evaluates to the empty
1449       string, the regexp in the last successful match is used instead.  So we
1450       have
1451
1452           "dog" =~ /d/;  # 'd' matches
1453           "dogbert =~ //;  # this matches the 'd' regexp used before
1454
1455       Global matching
1456
1457       The final two modifiers we will discuss here, "/g" and "/c", concern
1458       multiple matches.  The modifier "/g" stands for global matching and
1459       allows the matching operator to match within a string as many times as
1460       possible.  In scalar context, successive invocations against a string
1461       will have "/g" jump from match to match, keeping track of position in
1462       the string as it goes along.  You can get or set the position with the
1463       "pos()" function.
1464
1465       The use of "/g" is shown in the following example.  Suppose we have a
1466       string that consists of words separated by spaces.  If we know how many
1467       words there are in advance, we could extract the words using groupings:
1468
1469           $x = "cat dog house"; # 3 words
1470           $x =~ /^\s*(\w+)\s+(\w+)\s+(\w+)\s*$/; # matches,
1471                                                  # $1 = 'cat'
1472                                                  # $2 = 'dog'
1473                                                  # $3 = 'house'
1474
1475       But what if we had an indeterminate number of words? This is the sort
1476       of task "/g" was made for.  To extract all words, form the simple
1477       regexp "(\w+)" and loop over all matches with "/(\w+)/g":
1478
1479           while ($x =~ /(\w+)/g) {
1480               print "Word is $1, ends at position ", pos $x, "\n";
1481           }
1482
1483       prints
1484
1485           Word is cat, ends at position 3
1486           Word is dog, ends at position 7
1487           Word is house, ends at position 13
1488
1489       A failed match or changing the target string resets the position.  If
1490       you don't want the position reset after failure to match, add the "/c",
1491       as in "/regexp/gc".  The current position in the string is associated
1492       with the string, not the regexp.  This means that different strings
1493       have different positions and their respective positions can be set or
1494       read independently.
1495
1496       In list context, "/g" returns a list of matched groupings, or if there
1497       are no groupings, a list of matches to the whole regexp.  So if we
1498       wanted just the words, we could use
1499
1500           @words = ($x =~ /(\w+)/g);  # matches,
1501                                       # $words[0] = 'cat'
1502                                       # $words[1] = 'dog'
1503                                       # $words[2] = 'house'
1504
1505       Closely associated with the "/g" modifier is the "\G" anchor.  The "\G"
1506       anchor matches at the point where the previous "/g" match left off.
1507       "\G" allows us to easily do context-sensitive matching:
1508
1509           $metric = 1;  # use metric units
1510           ...
1511           $x = <FILE>;  # read in measurement
1512           $x =~ /^([+-]?\d+)\s*/g;  # get magnitude
1513           $weight = $1;
1514           if ($metric) { # error checking
1515               print "Units error!" unless $x =~ /\Gkg\./g;
1516           }
1517           else {
1518               print "Units error!" unless $x =~ /\Glbs\./g;
1519           }
1520           $x =~ /\G\s+(widget|sprocket)/g;  # continue processing
1521
1522       The combination of "/g" and "\G" allows us to process the string a bit
1523       at a time and use arbitrary Perl logic to decide what to do next.
1524       Currently, the "\G" anchor is only fully supported when used to anchor
1525       to the start of the pattern.
1526
1527       "\G" is also invaluable in processing fixed-length records with
1528       regexps.  Suppose we have a snippet of coding region DNA, encoded as
1529       base pair letters "ATCGTTGAAT..." and we want to find all the stop
1530       codons "TGA".  In a coding region, codons are 3-letter sequences, so we
1531       can think of the DNA snippet as a sequence of 3-letter records.  The
1532       naive regexp
1533
1534           # expanded, this is "ATC GTT GAA TGC AAA TGA CAT GAC"
1535           $dna = "ATCGTTGAATGCAAATGACATGAC";
1536           $dna =~ /TGA/;
1537
1538       doesn't work; it may match a "TGA", but there is no guarantee that the
1539       match is aligned with codon boundaries, e.g., the substring "GTT GAA"
1540       gives a match.  A better solution is
1541
1542           while ($dna =~ /(\w\w\w)*?TGA/g) {  # note the minimal *?
1543               print "Got a TGA stop codon at position ", pos $dna, "\n";
1544           }
1545
1546       which prints
1547
1548           Got a TGA stop codon at position 18
1549           Got a TGA stop codon at position 23
1550
1551       Position 18 is good, but position 23 is bogus.  What happened?
1552
1553       The answer is that our regexp works well until we get past the last
1554       real match.  Then the regexp will fail to match a synchronized "TGA"
1555       and start stepping ahead one character position at a time, not what we
1556       want.  The solution is to use "\G" to anchor the match to the codon
1557       alignment:
1558
1559           while ($dna =~ /\G(\w\w\w)*?TGA/g) {
1560               print "Got a TGA stop codon at position ", pos $dna, "\n";
1561           }
1562
1563       This prints
1564
1565           Got a TGA stop codon at position 18
1566
1567       which is the correct answer.  This example illustrates that it is
1568       important not only to match what is desired, but to reject what is not
1569       desired.
1570
1571       (There are other regexp modifiers that are available, such as "/o", but
1572       their specialized uses are beyond the scope of this introduction.  )
1573
1574       Search and replace
1575
1576       Regular expressions also play a big role in search and replace
1577       operations in Perl.  Search and replace is accomplished with the "s///"
1578       operator.  The general form is "s/regexp/replacement/modifiers", with
1579       everything we know about regexps and modifiers applying in this case as
1580       well.  The replacement is a Perl double-quoted string that replaces in
1581       the string whatever is matched with the "regexp".  The operator "=~" is
1582       also used here to associate a string with "s///".  If matching against
1583       $_, the "$_ =~" can be dropped.  If there is a match, "s///" returns
1584       the number of substitutions made; otherwise it returns false.  Here are
1585       a few examples:
1586
1587           $x = "Time to feed the cat!";
1588           $x =~ s/cat/hacker/;   # $x contains "Time to feed the hacker!"
1589           if ($x =~ s/^(Time.*hacker)!$/$1 now!/) {
1590               $more_insistent = 1;
1591           }
1592           $y = "'quoted words'";
1593           $y =~ s/^'(.*)'$/$1/;  # strip single quotes,
1594                                  # $y contains "quoted words"
1595
1596       In the last example, the whole string was matched, but only the part
1597       inside the single quotes was grouped.  With the "s///" operator, the
1598       matched variables $1, $2, etc. are immediately available for use in the
1599       replacement expression, so we use $1 to replace the quoted string with
1600       just what was quoted.  With the global modifier, "s///g" will search
1601       and replace all occurrences of the regexp in the string:
1602
1603           $x = "I batted 4 for 4";
1604           $x =~ s/4/four/;   # doesn't do it all:
1605                              # $x contains "I batted four for 4"
1606           $x = "I batted 4 for 4";
1607           $x =~ s/4/four/g;  # does it all:
1608                              # $x contains "I batted four for four"
1609
1610       If you prefer "regex" over "regexp" in this tutorial, you could use the
1611       following program to replace it:
1612
1613           % cat > simple_replace
1614           #!/usr/bin/perl
1615           $regexp = shift;
1616           $replacement = shift;
1617           while (<>) {
1618               s/$regexp/$replacement/g;
1619               print;
1620           }
1621           ^D
1622
1623           % simple_replace regexp regex perlretut.pod
1624
1625       In "simple_replace" we used the "s///g" modifier to replace all
1626       occurrences of the regexp on each line.  (Even though the regular
1627       expression appears in a loop, Perl is smart enough to compile it only
1628       once.)  As with "simple_grep", both the "print" and the
1629       "s/$regexp/$replacement/g" use $_ implicitly.
1630
1631       If you don't want "s///" to change your original variable you can use
1632       the non-destructive substitute modifier, "s///r".  This changes the
1633       behavior so that "s///r" returns the final substituted string (instead
1634       of the number of substitutions):
1635
1636           $x = "I like dogs.";
1637           $y = $x =~ s/dogs/cats/r;
1638           print "$x $y\n";
1639
1640       That example will print "I like dogs. I like cats". Notice the original
1641       $x variable has not been affected. The overall result of the
1642       substitution is instead stored in $y. If the substitution doesn't
1643       affect anything then the original string is returned:
1644
1645           $x = "I like dogs.";
1646           $y = $x =~ s/elephants/cougars/r;
1647           print "$x $y\n"; # prints "I like dogs. I like dogs."
1648
1649       One other interesting thing that the "s///r" flag allows is chaining
1650       substitutions:
1651
1652           $x = "Cats are great.";
1653           print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~
1654               s/Frogs/Hedgehogs/r, "\n";
1655           # prints "Hedgehogs are great."
1656
1657       A modifier available specifically to search and replace is the "s///e"
1658       evaluation modifier.  "s///e" treats the replacement text as Perl code,
1659       rather than a double-quoted string.  The value that the code returns is
1660       substituted for the matched substring.  "s///e" is useful if you need
1661       to do a bit of computation in the process of replacing text.  This
1662       example counts character frequencies in a line:
1663
1664           $x = "Bill the cat";
1665           $x =~ s/(.)/$chars{$1}++;$1/eg; # final $1 replaces char with itself
1666           print "frequency of '$_' is $chars{$_}\n"
1667               foreach (sort {$chars{$b} <=> $chars{$a}} keys %chars);
1668
1669       This prints
1670
1671           frequency of ' ' is 2
1672           frequency of 't' is 2
1673           frequency of 'l' is 2
1674           frequency of 'B' is 1
1675           frequency of 'c' is 1
1676           frequency of 'e' is 1
1677           frequency of 'h' is 1
1678           frequency of 'i' is 1
1679           frequency of 'a' is 1
1680
1681       As with the match "m//" operator, "s///" can use other delimiters, such
1682       as "s!!!" and "s{}{}", and even "s{}//".  If single quotes are used
1683       "s'''", then the regexp and replacement are treated as single-quoted
1684       strings and there are no variable substitutions.  "s///" in list
1685       context returns the same thing as in scalar context, i.e., the number
1686       of matches.
1687
1688       The split function
1689
1690       The "split()" function is another place where a regexp is used.  "split
1691       /regexp/, string, limit" separates the "string" operand into a list of
1692       substrings and returns that list.  The regexp must be designed to match
1693       whatever constitutes the separators for the desired substrings.  The
1694       "limit", if present, constrains splitting into no more than "limit"
1695       number of strings.  For example, to split a string into words, use
1696
1697           $x = "Calvin and Hobbes";
1698           @words = split /\s+/, $x;  # $word[0] = 'Calvin'
1699                                      # $word[1] = 'and'
1700                                      # $word[2] = 'Hobbes'
1701
1702       If the empty regexp "//" is used, the regexp always matches and the
1703       string is split into individual characters.  If the regexp has
1704       groupings, then the resulting list contains the matched substrings from
1705       the groupings as well.  For instance,
1706
1707           $x = "/usr/bin/perl";
1708           @dirs = split m!/!, $x;  # $dirs[0] = ''
1709                                    # $dirs[1] = 'usr'
1710                                    # $dirs[2] = 'bin'
1711                                    # $dirs[3] = 'perl'
1712           @parts = split m!(/)!, $x;  # $parts[0] = ''
1713                                       # $parts[1] = '/'
1714                                       # $parts[2] = 'usr'
1715                                       # $parts[3] = '/'
1716                                       # $parts[4] = 'bin'
1717                                       # $parts[5] = '/'
1718                                       # $parts[6] = 'perl'
1719
1720       Since the first character of $x matched the regexp, "split" prepended
1721       an empty initial element to the list.
1722
1723       If you have read this far, congratulations! You now have all the basic
1724       tools needed to use regular expressions to solve a wide range of text
1725       processing problems.  If this is your first time through the tutorial,
1726       why not stop here and play around with regexps a while....  Part 2
1727       concerns the more esoteric aspects of regular expressions and those
1728       concepts certainly aren't needed right at the start.
1729

Part 2: Power tools

1731       OK, you know the basics of regexps and you want to know more.  If
1732       matching regular expressions is analogous to a walk in the woods, then
1733       the tools discussed in Part 1 are analogous to topo maps and a compass,
1734       basic tools we use all the time.  Most of the tools in part 2 are
1735       analogous to flare guns and satellite phones.  They aren't used too
1736       often on a hike, but when we are stuck, they can be invaluable.
1737
1738       What follows are the more advanced, less used, or sometimes esoteric
1739       capabilities of Perl regexps.  In Part 2, we will assume you are
1740       comfortable with the basics and concentrate on the advanced features.
1741
1742   More on characters, strings, and character classes
1743       There are a number of escape sequences and character classes that we
1744       haven't covered yet.
1745
1746       There are several escape sequences that convert characters or strings
1747       between upper and lower case, and they are also available within
1748       patterns.  "\l" and "\u" convert the next character to lower or upper
1749       case, respectively:
1750
1751           $x = "perl";
1752           $string =~ /\u$x/;  # matches 'Perl' in $string
1753           $x = "M(rs?|s)\\."; # note the double backslash
1754           $string =~ /\l$x/;  # matches 'mr.', 'mrs.', and 'ms.',
1755
1756       A "\L" or "\U" indicates a lasting conversion of case, until terminated
1757       by "\E" or thrown over by another "\U" or "\L":
1758
1759           $x = "This word is in lower case:\L SHOUT\E";
1760           $x =~ /shout/;       # matches
1761           $x = "I STILL KEYPUNCH CARDS FOR MY 360"
1762           $x =~ /\Ukeypunch/;  # matches punch card string
1763
1764       If there is no "\E", case is converted until the end of the string. The
1765       regexps "\L\u$word" or "\u\L$word" convert the first character of $word
1766       to uppercase and the rest of the characters to lowercase.
1767
1768       Control characters can be escaped with "\c", so that a control-Z
1769       character would be matched with "\cZ".  The escape sequence "\Q"..."\E"
1770       quotes, or protects most non-alphabetic characters.   For instance,
1771
1772           $x = "\QThat !^*&%~& cat!";
1773           $x =~ /\Q!^*&%~&\E/;  # check for rough language
1774
1775       It does not protect '$' or '@', so that variables can still be
1776       substituted.
1777
1778       "\Q", "\L", "\l", "\U", "\u" and "\E" are actually part of double-
1779       quotish syntax, and not part of regexp syntax proper.  They will work
1780       if they appear in a regular expression embedded directly in a program,
1781       but not when contained in a string that is interpolated in a pattern.
1782
1783       Perl regexps can handle more than just the standard ASCII character
1784       set.  Perl supports Unicode, a standard for representing the alphabets
1785       from virtually all of the world's written languages, and a host of
1786       symbols.  Perl's text strings are Unicode strings, so they can contain
1787       characters with a value (codepoint or character number) higher than
1788       255.
1789
1790       What does this mean for regexps? Well, regexp users don't need to know
1791       much about Perl's internal representation of strings.  But they do need
1792       to know 1) how to represent Unicode characters in a regexp and 2) that
1793       a matching operation will treat the string to be searched as a sequence
1794       of characters, not bytes.  The answer to 1) is that Unicode characters
1795       greater than "chr(255)" are represented using the "\x{hex}" notation,
1796       because "\x"XY (without curly braces and XY are two hex digits) doesn't
1797       go further than 255.  (Starting in Perl 5.14, if you're an octal fan,
1798       you can also use "\o{oct}".)
1799
1800           /\x{263a}/;  # match a Unicode smiley face :)
1801
1802       NOTE: In Perl 5.6.0 it used to be that one needed to say "use utf8" to
1803       use any Unicode features.  This is no more the case: for almost all
1804       Unicode processing, the explicit "utf8" pragma is not needed.  (The
1805       only case where it matters is if your Perl script is in Unicode and
1806       encoded in UTF-8, then an explicit "use utf8" is needed.)
1807
1808       Figuring out the hexadecimal sequence of a Unicode character you want
1809       or deciphering someone else's hexadecimal Unicode regexp is about as
1810       much fun as programming in machine code.  So another way to specify
1811       Unicode characters is to use the named character escape sequence
1812       "\N{name}".  name is a name for the Unicode character, as specified in
1813       the Unicode standard.  For instance, if we wanted to represent or match
1814       the astrological sign for the planet Mercury, we could use
1815
1816           $x = "abc\N{MERCURY}def";
1817           $x =~ /\N{MERCURY}/;   # matches
1818
1819       One can also use "short" names:
1820
1821           print "\N{GREEK SMALL LETTER SIGMA} is called sigma.\n";
1822           print "\N{greek:Sigma} is an upper-case sigma.\n";
1823
1824       You can also restrict names to a certain alphabet by specifying the
1825       charnames pragma:
1826
1827           use charnames qw(greek);
1828           print "\N{sigma} is Greek sigma\n";
1829
1830       An index of character names is available on-line from the Unicode
1831       Consortium, <http://www.unicode.org/charts/charindex.html>; explanatory
1832       material with links to other resources at
1833       <http://www.unicode.org/standard/where>.
1834
1835       The answer to requirement 2) is that a regexp (mostly) uses Unicode
1836       characters.  The "mostly" is for messy backward compatibility reasons,
1837       but starting in Perl 5.14, any regexp compiled in the scope of a "use
1838       feature 'unicode_strings'" (which is automatically turned on within the
1839       scope of a "use 5.012" or higher) will turn that "mostly" into
1840       "always".  If you want to handle Unicode properly, you should ensure
1841       that 'unicode_strings' is turned on.  Internally, this is encoded to
1842       bytes using either UTF-8 or a native 8 bit encoding, depending on the
1843       history of the string, but conceptually it is a sequence of characters,
1844       not bytes. See perlunitut for a tutorial about that.
1845
1846       Let us now discuss Unicode character classes, most usually called
1847       "character properties".  These are represented by the "\p{name}" escape
1848       sequence.  The negation of this is "\P{name}".  For example, to match
1849       lower and uppercase characters,
1850
1851           $x = "BOB";
1852           $x =~ /^\p{IsUpper}/;   # matches, uppercase char class
1853           $x =~ /^\P{IsUpper}/;   # doesn't match, char class sans uppercase
1854           $x =~ /^\p{IsLower}/;   # doesn't match, lowercase char class
1855           $x =~ /^\P{IsLower}/;   # matches, char class sans lowercase
1856
1857       (The ""Is"" is optional.)
1858
1859       There are many, many Unicode character properties.  For the full list
1860       see perluniprops.  Most of them have synonyms with shorter names, also
1861       listed there.  Some synonyms are a single character.  For these, you
1862       can drop the braces.  For instance, "\pM" is the same thing as
1863       "\p{Mark}", meaning things like accent marks.
1864
1865       The Unicode "\p{Script}" and "\p{Script_Extensions}" properties are
1866       used to categorize every Unicode character into the language script it
1867       is written in.  ("Script_Extensions" is an improved version of
1868       "Script", which is retained for backward compatibility, and so you
1869       should generally use "Script_Extensions".)  For example, English,
1870       French, and a bunch of other European languages are written in the
1871       Latin script.  But there is also the Greek script, the Thai script, the
1872       Katakana script, etc.  You can test whether a character is in a
1873       particular script (based on "Script_Extensions") with, for example
1874       "\p{Latin}", "\p{Greek}", or "\p{Katakana}".  To test if it isn't in
1875       the Balinese script, you would use "\P{Balinese}".
1876
1877       What we have described so far is the single form of the "\p{...}"
1878       character classes.  There is also a compound form which you may run
1879       into.  These look like "\p{name=value}" or "\p{name:value}" (the equals
1880       sign and colon can be used interchangeably).  These are more general
1881       than the single form, and in fact most of the single forms are just
1882       Perl-defined shortcuts for common compound forms.  For example, the
1883       script examples in the previous paragraph could be written equivalently
1884       as "\p{Script_Extensions=Latin}", "\p{Script_Extensions:Greek}",
1885       "\p{script_extensions=katakana}", and "\P{script_extensions=balinese}"
1886       (case is irrelevant between the "{}" braces).  You may never have to
1887       use the compound forms, but sometimes it is necessary, and their use
1888       can make your code easier to understand.
1889
1890       "\X" is an abbreviation for a character class that comprises a Unicode
1891       extended grapheme cluster.  This represents a "logical character": what
1892       appears to be a single character, but may be represented internally by
1893       more than one.  As an example, using the Unicode full names, e.g.,
1894       "A + COMBINING RING" is a grapheme cluster with base character "A" and
1895       combining character "COMBINING RING, which translates in Danish to "A"
1896       with the circle atop it, as in the word Aangstrom.
1897
1898       For the full and latest information about Unicode see the latest
1899       Unicode standard, or the Unicode Consortium's website
1900       <http://www.unicode.org>
1901
1902       As if all those classes weren't enough, Perl also defines POSIX-style
1903       character classes.  These have the form "[:name:]", with name the name
1904       of the POSIX class.  The POSIX classes are "alpha", "alnum", "ascii",
1905       "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper",
1906       and "xdigit", and two extensions, "word" (a Perl extension to match
1907       "\w"), and "blank" (a GNU extension).  The "/a" modifier restricts
1908       these to matching just in the ASCII range; otherwise they can match the
1909       same as their corresponding Perl Unicode classes: "[:upper:]" is the
1910       same as "\p{IsUpper}", etc.  (There are some exceptions and gotchas
1911       with this; see perlrecharclass for a full discussion.) The "[:digit:]",
1912       "[:word:]", and "[:space:]" correspond to the familiar "\d", "\w", and
1913       "\s" character classes.  To negate a POSIX class, put a '^' in front of
1914       the name, so that, e.g., "[:^digit:]" corresponds to "\D" and, under
1915       Unicode, "\P{IsDigit}".  The Unicode and POSIX character classes can be
1916       used just like "\d", with the exception that POSIX character classes
1917       can only be used inside of a character class:
1918
1919           /\s+[abc[:digit:]xyz]\s*/;  # match a,b,c,x,y,z, or a digit
1920           /^=item\s[[:digit:]]/;      # match '=item',
1921                                       # followed by a space and a digit
1922           /\s+[abc\p{IsDigit}xyz]\s+/;  # match a,b,c,x,y,z, or a digit
1923           /^=item\s\p{IsDigit}/;        # match '=item',
1924                                         # followed by a space and a digit
1925
1926       Whew! That is all the rest of the characters and character classes.
1927
1928   Compiling and saving regular expressions
1929       In Part 1 we mentioned that Perl compiles a regexp into a compact
1930       sequence of opcodes.  Thus, a compiled regexp is a data structure that
1931       can be stored once and used again and again.  The regexp quote "qr//"
1932       does exactly that: "qr/string/" compiles the "string" as a regexp and
1933       transforms the result into a form that can be assigned to a variable:
1934
1935           $reg = qr/foo+bar?/;  # reg contains a compiled regexp
1936
1937       Then $reg can be used as a regexp:
1938
1939           $x = "fooooba";
1940           $x =~ $reg;     # matches, just like /foo+bar?/
1941           $x =~ /$reg/;   # same thing, alternate form
1942
1943       $reg can also be interpolated into a larger regexp:
1944
1945           $x =~ /(abc)?$reg/;  # still matches
1946
1947       As with the matching operator, the regexp quote can use different
1948       delimiters, e.g., "qr!!", "qr{}" or "qr~~".  Apostrophes as delimiters
1949       ("qr''") inhibit any interpolation.
1950
1951       Pre-compiled regexps are useful for creating dynamic matches that don't
1952       need to be recompiled each time they are encountered.  Using pre-
1953       compiled regexps, we write a "grep_step" program which greps for a
1954       sequence of patterns, advancing to the next pattern as soon as one has
1955       been satisfied.
1956
1957           % cat > grep_step
1958           #!/usr/bin/perl
1959           # grep_step - match <number> regexps, one after the other
1960           # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
1961
1962           $number = shift;
1963           $regexp[$_] = shift foreach (0..$number-1);
1964           @compiled = map qr/$_/, @regexp;
1965           while ($line = <>) {
1966               if ($line =~ /$compiled[0]/) {
1967                   print $line;
1968                   shift @compiled;
1969                   last unless @compiled;
1970               }
1971           }
1972           ^D
1973
1974           % grep_step 3 shift print last grep_step
1975           $number = shift;
1976                   print $line;
1977                   last unless @compiled;
1978
1979       Storing pre-compiled regexps in an array @compiled allows us to simply
1980       loop through the regexps without any recompilation, thus gaining
1981       flexibility without sacrificing speed.
1982
1983   Composing regular expressions at runtime
1984       Backtracking is more efficient than repeated tries with different
1985       regular expressions.  If there are several regular expressions and a
1986       match with any of them is acceptable, then it is possible to combine
1987       them into a set of alternatives.  If the individual expressions are
1988       input data, this can be done by programming a join operation.  We'll
1989       exploit this idea in an improved version of the "simple_grep" program:
1990       a program that matches multiple patterns:
1991
1992           % cat > multi_grep
1993           #!/usr/bin/perl
1994           # multi_grep - match any of <number> regexps
1995           # usage: multi_grep <number> regexp1 regexp2 ... file1 file2 ...
1996
1997           $number = shift;
1998           $regexp[$_] = shift foreach (0..$number-1);
1999           $pattern = join '|', @regexp;
2000
2001           while ($line = <>) {
2002               print $line if $line =~ /$pattern/;
2003           }
2004           ^D
2005
2006           % multi_grep 2 shift for multi_grep
2007           $number = shift;
2008           $regexp[$_] = shift foreach (0..$number-1);
2009
2010       Sometimes it is advantageous to construct a pattern from the input that
2011       is to be analyzed and use the permissible values on the left hand side
2012       of the matching operations.  As an example for this somewhat
2013       paradoxical situation, let's assume that our input contains a command
2014       verb which should match one out of a set of available command verbs,
2015       with the additional twist that commands may be abbreviated as long as
2016       the given string is unique. The program below demonstrates the basic
2017       algorithm.
2018
2019           % cat > keymatch
2020           #!/usr/bin/perl
2021           $kwds = 'copy compare list print';
2022           while( $cmd = <> ){
2023               $cmd =~ s/^\s+|\s+$//g;  # trim leading and trailing spaces
2024               if( ( @matches = $kwds =~ /\b$cmd\w*/g ) == 1 ){
2025                   print "command: '@matches'\n";
2026               } elsif( @matches == 0 ){
2027                   print "no such command: '$cmd'\n";
2028               } else {
2029                   print "not unique: '$cmd' (could be one of: @matches)\n";
2030               }
2031           }
2032           ^D
2033
2034           % keymatch
2035           li
2036           command: 'list'
2037           co
2038           not unique: 'co' (could be one of: copy compare)
2039           printer
2040           no such command: 'printer'
2041
2042       Rather than trying to match the input against the keywords, we match
2043       the combined set of keywords against the input.  The pattern matching
2044       operation "$kwds =~ /\b($cmd\w*)/g" does several things at the same
2045       time. It makes sure that the given command begins where a keyword
2046       begins ("\b"). It tolerates abbreviations due to the added "\w*". It
2047       tells us the number of matches ("scalar @matches") and all the keywords
2048       that were actually matched.  You could hardly ask for more.
2049
2050   Embedding comments and modifiers in a regular expression
2051       Starting with this section, we will be discussing Perl's set of
2052       extended patterns.  These are extensions to the traditional regular
2053       expression syntax that provide powerful new tools for pattern matching.
2054       We have already seen extensions in the form of the minimal matching
2055       constructs "??", "*?", "+?", "{n,m}?", and "{n,}?".  Most of the
2056       extensions below have the form "(?char...)", where the "char" is a
2057       character that determines the type of extension.
2058
2059       The first extension is an embedded comment "(?#text)".  This embeds a
2060       comment into the regular expression without affecting its meaning.  The
2061       comment should not have any closing parentheses in the text.  An
2062       example is
2063
2064           /(?# Match an integer:)[+-]?\d+/;
2065
2066       This style of commenting has been largely superseded by the raw,
2067       freeform commenting that is allowed with the "/x" modifier.
2068
2069       Most modifiers, such as "/i", "/m", "/s" and "/x" (or any combination
2070       thereof) can also be embedded in a regexp using "(?i)", "(?m)", "(?s)",
2071       and "(?x)".  For instance,
2072
2073           /(?i)yes/;  # match 'yes' case insensitively
2074           /yes/i;     # same thing
2075           /(?x)(          # freeform version of an integer regexp
2076                    [+-]?  # match an optional sign
2077                    \d+    # match a sequence of digits
2078                )
2079           /x;
2080
2081       Embedded modifiers can have two important advantages over the usual
2082       modifiers.  Embedded modifiers allow a custom set of modifiers for each
2083       regexp pattern.  This is great for matching an array of regexps that
2084       must have different modifiers:
2085
2086           $pattern[0] = '(?i)doctor';
2087           $pattern[1] = 'Johnson';
2088           ...
2089           while (<>) {
2090               foreach $patt (@pattern) {
2091                   print if /$patt/;
2092               }
2093           }
2094
2095       The second advantage is that embedded modifiers (except "/p", which
2096       modifies the entire regexp) only affect the regexp inside the group the
2097       embedded modifier is contained in.  So grouping can be used to localize
2098       the modifier's effects:
2099
2100           /Answer: ((?i)yes)/;  # matches 'Answer: yes', 'Answer: YES', etc.
2101
2102       Embedded modifiers can also turn off any modifiers already present by
2103       using, e.g., "(?-i)".  Modifiers can also be combined into a single
2104       expression, e.g., "(?s-i)" turns on single line mode and turns off case
2105       insensitivity.
2106
2107       Embedded modifiers may also be added to a non-capturing grouping.
2108       "(?i-m:regexp)" is a non-capturing grouping that matches "regexp" case
2109       insensitively and turns off multi-line mode.
2110
2111   Looking ahead and looking behind
2112       This section concerns the lookahead and lookbehind assertions.  First,
2113       a little background.
2114
2115       In Perl regular expressions, most regexp elements "eat up" a certain
2116       amount of string when they match.  For instance, the regexp element
2117       "[abc]" eats up one character of the string when it matches, in the
2118       sense that Perl moves to the next character position in the string
2119       after the match.  There are some elements, however, that don't eat up
2120       characters (advance the character position) if they match.  The
2121       examples we have seen so far are the anchors.  The anchor '^' matches
2122       the beginning of the line, but doesn't eat any characters.  Similarly,
2123       the word boundary anchor "\b" matches wherever a character matching
2124       "\w" is next to a character that doesn't, but it doesn't eat up any
2125       characters itself.  Anchors are examples of zero-width assertions:
2126       zero-width, because they consume no characters, and assertions, because
2127       they test some property of the string.  In the context of our walk in
2128       the woods analogy to regexp matching, most regexp elements move us
2129       along a trail, but anchors have us stop a moment and check our
2130       surroundings.  If the local environment checks out, we can proceed
2131       forward.  But if the local environment doesn't satisfy us, we must
2132       backtrack.
2133
2134       Checking the environment entails either looking ahead on the trail,
2135       looking behind, or both.  '^' looks behind, to see that there are no
2136       characters before.  '$' looks ahead, to see that there are no
2137       characters after.  "\b" looks both ahead and behind, to see if the
2138       characters on either side differ in their "word-ness".
2139
2140       The lookahead and lookbehind assertions are generalizations of the
2141       anchor concept.  Lookahead and lookbehind are zero-width assertions
2142       that let us specify which characters we want to test for.  The
2143       lookahead assertion is denoted by "(?=regexp)" and the lookbehind
2144       assertion is denoted by "(?<=fixed-regexp)".  Some examples are
2145
2146           $x = "I catch the housecat 'Tom-cat' with catnip";
2147           $x =~ /cat(?=\s)/;   # matches 'cat' in 'housecat'
2148           @catwords = ($x =~ /(?<=\s)cat\w+/g);  # matches,
2149                                                  # $catwords[0] = 'catch'
2150                                                  # $catwords[1] = 'catnip'
2151           $x =~ /\bcat\b/;  # matches 'cat' in 'Tom-cat'
2152           $x =~ /(?<=\s)cat(?=\s)/; # doesn't match; no isolated 'cat' in
2153                                     # middle of $x
2154
2155       Note that the parentheses in "(?=regexp)" and "(?<=regexp)" are non-
2156       capturing, since these are zero-width assertions.  Thus in the second
2157       regexp, the substrings captured are those of the whole regexp itself.
2158       Lookahead "(?=regexp)" can match arbitrary regexps, but lookbehind
2159       "(?<=fixed-regexp)" only works for regexps of fixed width, i.e., a
2160       fixed number of characters long.  Thus "(?<=(ab|bc))" is fine, but
2161       "(?<=(ab)*)" is not.  The negated versions of the lookahead and
2162       lookbehind assertions are denoted by "(?!regexp)" and
2163       "(?<!fixed-regexp)" respectively.  They evaluate true if the regexps do
2164       not match:
2165
2166           $x = "foobar";
2167           $x =~ /foo(?!bar)/;  # doesn't match, 'bar' follows 'foo'
2168           $x =~ /foo(?!baz)/;  # matches, 'baz' doesn't follow 'foo'
2169           $x =~ /(?<!\s)foo/;  # matches, there is no \s before 'foo'
2170
2171       Here is an example where a string containing blank-separated words,
2172       numbers and single dashes is to be split into its components.  Using
2173       "/\s+/" alone won't work, because spaces are not required between
2174       dashes, or a word or a dash. Additional places for a split are
2175       established by looking ahead and behind:
2176
2177           $str = "one two - --6-8";
2178           @toks = split / \s+              # a run of spaces
2179                         | (?<=\S) (?=-)    # any non-space followed by '-'
2180                         | (?<=-)  (?=\S)   # a '-' followed by any non-space
2181                         /x, $str;          # @toks = qw(one two - - - 6 - 8)
2182
2183       Starting in Perl 5.28, experimentally, alphabetic equivalents to these
2184       assertions are added, so you can use whichever is most memorable for
2185       your tastes.
2186
2187        (?=...)        (*pla:...) or (*positive_lookahead:...)
2188        (?!...)        (*nla:...) or (*negative_lookahead:...)
2189        (?<=...)       (*plb:...) or (*positive_lookbehind:...)
2190        (?<!...)       (*nlb:...) or (*negative_lookbehind:...)
2191        (?>...)        (*atomic:...)
2192
2193       Using any of these will raise (unless turned off) a warning in the
2194       "experimental::alpha_assertions" category.
2195
2196   Using independent subexpressions to prevent backtracking
2197       Independent subexpressions are regular expressions, in the context of a
2198       larger regular expression, that function independently of the larger
2199       regular expression.  That is, they consume as much or as little of the
2200       string as they wish without regard for the ability of the larger regexp
2201       to match.  Independent subexpressions are represented by "(?>regexp)".
2202       We can illustrate their behavior by first considering an ordinary
2203       regexp:
2204
2205           $x = "ab";
2206           $x =~ /a*ab/;  # matches
2207
2208       This obviously matches, but in the process of matching, the
2209       subexpression "a*" first grabbed the 'a'.  Doing so, however, wouldn't
2210       allow the whole regexp to match, so after backtracking, "a*" eventually
2211       gave back the 'a' and matched the empty string.  Here, what "a*"
2212       matched was dependent on what the rest of the regexp matched.
2213
2214       Contrast that with an independent subexpression:
2215
2216           $x =~ /(?>a*)ab/;  # doesn't match!
2217
2218       The independent subexpression "(?>a*)" doesn't care about the rest of
2219       the regexp, so it sees an 'a' and grabs it.  Then the rest of the
2220       regexp "ab" cannot match.  Because "(?>a*)" is independent, there is no
2221       backtracking and the independent subexpression does not give up its
2222       'a'.  Thus the match of the regexp as a whole fails.  A similar
2223       behavior occurs with completely independent regexps:
2224
2225           $x = "ab";
2226           $x =~ /a*/g;   # matches, eats an 'a'
2227           $x =~ /\Gab/g; # doesn't match, no 'a' available
2228
2229       Here "/g" and "\G" create a "tag team" handoff of the string from one
2230       regexp to the other.  Regexps with an independent subexpression are
2231       much like this, with a handoff of the string to the independent
2232       subexpression, and a handoff of the string back to the enclosing
2233       regexp.
2234
2235       The ability of an independent subexpression to prevent backtracking can
2236       be quite useful.  Suppose we want to match a non-empty string enclosed
2237       in parentheses up to two levels deep.  Then the following regexp
2238       matches:
2239
2240           $x = "abc(de(fg)h";  # unbalanced parentheses
2241           $x =~ /\( ( [ ^ () ]+ | \( [ ^ () ]* \) )+ \)/xx;
2242
2243       The regexp matches an open parenthesis, one or more copies of an
2244       alternation, and a close parenthesis.  The alternation is two-way, with
2245       the first alternative "[^()]+" matching a substring with no parentheses
2246       and the second alternative "\([^()]*\)"  matching a substring delimited
2247       by parentheses.  The problem with this regexp is that it is
2248       pathological: it has nested indeterminate quantifiers of the form
2249       "(a+|b)+".  We discussed in Part 1 how nested quantifiers like this
2250       could take an exponentially long time to execute if there was no match
2251       possible.  To prevent the exponential blowup, we need to prevent
2252       useless backtracking at some point.  This can be done by enclosing the
2253       inner quantifier as an independent subexpression:
2254
2255           $x =~ /\( ( (?> [ ^ () ]+ ) | \([ ^ () ]* \) )+ \)/xx;
2256
2257       Here, "(?>[^()]+)" breaks the degeneracy of string partitioning by
2258       gobbling up as much of the string as possible and keeping it.   Then
2259       match failures fail much more quickly.
2260
2261   Conditional expressions
2262       A conditional expression is a form of if-then-else statement that
2263       allows one to choose which patterns are to be matched, based on some
2264       condition.  There are two types of conditional expression:
2265       "(?(condition)yes-regexp)" and "(?(condition)yes-regexp|no-regexp)".
2266       "(?(condition)yes-regexp)" is like an 'if () {}' statement in Perl.  If
2267       the condition is true, the yes-regexp will be matched.  If the
2268       condition is false, the yes-regexp will be skipped and Perl will move
2269       onto the next regexp element.  The second form is like an
2270       'if () {} else {}' statement in Perl.  If the condition is true, the
2271       yes-regexp will be matched, otherwise the no-regexp will be matched.
2272
2273       The condition can have several forms.  The first form is simply an
2274       integer in parentheses "(integer)".  It is true if the corresponding
2275       backreference "\integer" matched earlier in the regexp.  The same thing
2276       can be done with a name associated with a capture group, written as
2277       "(<name>)" or "('name')".  The second form is a bare zero-width
2278       assertion "(?...)", either a lookahead, a lookbehind, or a code
2279       assertion (discussed in the next section).  The third set of forms
2280       provides tests that return true if the expression is executed within a
2281       recursion ("(R)") or is being called from some capturing group,
2282       referenced either by number ("(R1)", "(R2)",...) or by name
2283       ("(R&name)").
2284
2285       The integer or name form of the "condition" allows us to choose, with
2286       more flexibility, what to match based on what matched earlier in the
2287       regexp. This searches for words of the form "$x$x" or "$x$y$y$x":
2288
2289           % simple_grep '^(\w+)(\w+)?(?(2)\g2\g1|\g1)$' /usr/dict/words
2290           beriberi
2291           coco
2292           couscous
2293           deed
2294           ...
2295           toot
2296           toto
2297           tutu
2298
2299       The lookbehind "condition" allows, along with backreferences, an
2300       earlier part of the match to influence a later part of the match.  For
2301       instance,
2302
2303           /[ATGC]+(?(?<=AA)G|C)$/;
2304
2305       matches a DNA sequence such that it either ends in "AAG", or some other
2306       base pair combination and 'C'.  Note that the form is "(?(?<=AA)G|C)"
2307       and not "(?((?<=AA))G|C)"; for the lookahead, lookbehind or code
2308       assertions, the parentheses around the conditional are not needed.
2309
2310   Defining named patterns
2311       Some regular expressions use identical subpatterns in several places.
2312       Starting with Perl 5.10, it is possible to define named subpatterns in
2313       a section of the pattern so that they can be called up by name anywhere
2314       in the pattern.  This syntactic pattern for this definition group is
2315       "(?(DEFINE)(?<name>pattern)...)".  An insertion of a named pattern is
2316       written as "(?&name)".
2317
2318       The example below illustrates this feature using the pattern for
2319       floating point numbers that was presented earlier on.  The three
2320       subpatterns that are used more than once are the optional sign, the
2321       digit sequence for an integer and the decimal fraction.  The "DEFINE"
2322       group at the end of the pattern contains their definition.  Notice that
2323       the decimal fraction pattern is the first place where we can reuse the
2324       integer pattern.
2325
2326          /^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) )
2327             (?: [eE](?&osg)(?&int) )?
2328           $
2329           (?(DEFINE)
2330             (?<osg>[-+]?)         # optional sign
2331             (?<int>\d++)          # integer
2332             (?<dec>\.(?&int))     # decimal fraction
2333           )/x
2334
2335   Recursive patterns
2336       This feature (introduced in Perl 5.10) significantly extends the power
2337       of Perl's pattern matching.  By referring to some other capture group
2338       anywhere in the pattern with the construct "(?group-ref)", the pattern
2339       within the referenced group is used as an independent subpattern in
2340       place of the group reference itself.  Because the group reference may
2341       be contained within the group it refers to, it is now possible to apply
2342       pattern matching to tasks that hitherto required a recursive parser.
2343
2344       To illustrate this feature, we'll design a pattern that matches if a
2345       string contains a palindrome. (This is a word or a sentence that, while
2346       ignoring spaces, interpunctuation and case, reads the same backwards as
2347       forwards. We begin by observing that the empty string or a string
2348       containing just one word character is a palindrome. Otherwise it must
2349       have a word character up front and the same at its end, with another
2350       palindrome in between.
2351
2352           /(?: (\w) (?...Here be a palindrome...) \g{-1} | \w? )/x
2353
2354       Adding "\W*" at either end to eliminate what is to be ignored, we
2355       already have the full pattern:
2356
2357           my $pp = qr/^(\W* (?: (\w) (?1) \g{-1} | \w? ) \W*)$/ix;
2358           for $s ( "saippuakauppias", "A man, a plan, a canal: Panama!" ){
2359               print "'$s' is a palindrome\n" if $s =~ /$pp/;
2360           }
2361
2362       In "(?...)" both absolute and relative backreferences may be used.  The
2363       entire pattern can be reinserted with "(?R)" or "(?0)".  If you prefer
2364       to name your groups, you can use "(?&name)" to recurse into that group.
2365
2366   A bit of magic: executing Perl code in a regular expression
2367       Normally, regexps are a part of Perl expressions.  Code evaluation
2368       expressions turn that around by allowing arbitrary Perl code to be a
2369       part of a regexp.  A code evaluation expression is denoted "(?{code})",
2370       with code a string of Perl statements.
2371
2372       Code expressions are zero-width assertions, and the value they return
2373       depends on their environment.  There are two possibilities: either the
2374       code expression is used as a conditional in a conditional expression
2375       "(?(condition)...)", or it is not.  If the code expression is a
2376       conditional, the code is evaluated and the result (i.e., the result of
2377       the last statement) is used to determine truth or falsehood.  If the
2378       code expression is not used as a conditional, the assertion always
2379       evaluates true and the result is put into the special variable $^R.
2380       The variable $^R can then be used in code expressions later in the
2381       regexp.  Here are some silly examples:
2382
2383           $x = "abcdef";
2384           $x =~ /abc(?{print "Hi Mom!";})def/; # matches,
2385                                                # prints 'Hi Mom!'
2386           $x =~ /aaa(?{print "Hi Mom!";})def/; # doesn't match,
2387                                                # no 'Hi Mom!'
2388
2389       Pay careful attention to the next example:
2390
2391           $x =~ /abc(?{print "Hi Mom!";})ddd/; # doesn't match,
2392                                                # no 'Hi Mom!'
2393                                                # but why not?
2394
2395       At first glance, you'd think that it shouldn't print, because obviously
2396       the "ddd" isn't going to match the target string. But look at this
2397       example:
2398
2399           $x =~ /abc(?{print "Hi Mom!";})[dD]dd/; # doesn't match,
2400                                                   # but _does_ print
2401
2402       Hmm. What happened here? If you've been following along, you know that
2403       the above pattern should be effectively (almost) the same as the last
2404       one; enclosing the 'd' in a character class isn't going to change what
2405       it matches. So why does the first not print while the second one does?
2406
2407       The answer lies in the optimizations the regexp engine makes. In the
2408       first case, all the engine sees are plain old characters (aside from
2409       the "?{}" construct). It's smart enough to realize that the string
2410       'ddd' doesn't occur in our target string before actually running the
2411       pattern through. But in the second case, we've tricked it into thinking
2412       that our pattern is more complicated. It takes a look, sees our
2413       character class, and decides that it will have to actually run the
2414       pattern to determine whether or not it matches, and in the process of
2415       running it hits the print statement before it discovers that we don't
2416       have a match.
2417
2418       To take a closer look at how the engine does optimizations, see the
2419       section "Pragmas and debugging" below.
2420
2421       More fun with "?{}":
2422
2423           $x =~ /(?{print "Hi Mom!";})/;       # matches,
2424                                                # prints 'Hi Mom!'
2425           $x =~ /(?{$c = 1;})(?{print "$c";})/;  # matches,
2426                                                  # prints '1'
2427           $x =~ /(?{$c = 1;})(?{print "$^R";})/; # matches,
2428                                                  # prints '1'
2429
2430       The bit of magic mentioned in the section title occurs when the regexp
2431       backtracks in the process of searching for a match.  If the regexp
2432       backtracks over a code expression and if the variables used within are
2433       localized using "local", the changes in the variables produced by the
2434       code expression are undone! Thus, if we wanted to count how many times
2435       a character got matched inside a group, we could use, e.g.,
2436
2437           $x = "aaaa";
2438           $count = 0;  # initialize 'a' count
2439           $c = "bob";  # test if $c gets clobbered
2440           $x =~ /(?{local $c = 0;})         # initialize count
2441                  ( a                        # match 'a'
2442                    (?{local $c = $c + 1;})  # increment count
2443                  )*                         # do this any number of times,
2444                  aa                         # but match 'aa' at the end
2445                  (?{$count = $c;})          # copy local $c var into $count
2446                 /x;
2447           print "'a' count is $count, \$c variable is '$c'\n";
2448
2449       This prints
2450
2451           'a' count is 2, $c variable is 'bob'
2452
2453       If we replace the " (?{local $c = $c + 1;})" with " (?{$c = $c + 1;})",
2454       the variable changes are not undone during backtracking, and we get
2455
2456           'a' count is 4, $c variable is 'bob'
2457
2458       Note that only localized variable changes are undone.  Other side
2459       effects of code expression execution are permanent.  Thus
2460
2461           $x = "aaaa";
2462           $x =~ /(a(?{print "Yow\n";}))*aa/;
2463
2464       produces
2465
2466          Yow
2467          Yow
2468          Yow
2469          Yow
2470
2471       The result $^R is automatically localized, so that it will behave
2472       properly in the presence of backtracking.
2473
2474       This example uses a code expression in a conditional to match a
2475       definite article, either 'the' in English or 'der|die|das' in German:
2476
2477           $lang = 'DE';  # use German
2478           ...
2479           $text = "das";
2480           print "matched\n"
2481               if $text =~ /(?(?{
2482                                 $lang eq 'EN'; # is the language English?
2483                                })
2484                              the |             # if so, then match 'the'
2485                              (der|die|das)     # else, match 'der|die|das'
2486                            )
2487                           /xi;
2488
2489       Note that the syntax here is "(?(?{...})yes-regexp|no-regexp)", not
2490       "(?((?{...}))yes-regexp|no-regexp)".  In other words, in the case of a
2491       code expression, we don't need the extra parentheses around the
2492       conditional.
2493
2494       If you try to use code expressions where the code text is contained
2495       within an interpolated variable, rather than appearing literally in the
2496       pattern, Perl may surprise you:
2497
2498           $bar = 5;
2499           $pat = '(?{ 1 })';
2500           /foo(?{ $bar })bar/; # compiles ok, $bar not interpolated
2501           /foo(?{ 1 })$bar/;   # compiles ok, $bar interpolated
2502           /foo${pat}bar/;      # compile error!
2503
2504           $pat = qr/(?{ $foo = 1 })/;  # precompile code regexp
2505           /foo${pat}bar/;      # compiles ok
2506
2507       If a regexp has a variable that interpolates a code expression, Perl
2508       treats the regexp as an error. If the code expression is precompiled
2509       into a variable, however, interpolating is ok. The question is, why is
2510       this an error?
2511
2512       The reason is that variable interpolation and code expressions together
2513       pose a security risk.  The combination is dangerous because many
2514       programmers who write search engines often take user input and plug it
2515       directly into a regexp:
2516
2517           $regexp = <>;       # read user-supplied regexp
2518           $chomp $regexp;     # get rid of possible newline
2519           $text =~ /$regexp/; # search $text for the $regexp
2520
2521       If the $regexp variable contains a code expression, the user could then
2522       execute arbitrary Perl code.  For instance, some joker could search for
2523       "system('rm -rf *');" to erase your files.  In this sense, the
2524       combination of interpolation and code expressions taints your regexp.
2525       So by default, using both interpolation and code expressions in the
2526       same regexp is not allowed.  If you're not concerned about malicious
2527       users, it is possible to bypass this security check by invoking
2528       "use re 'eval'":
2529
2530           use re 'eval';       # throw caution out the door
2531           $bar = 5;
2532           $pat = '(?{ 1 })';
2533           /foo${pat}bar/;      # compiles ok
2534
2535       Another form of code expression is the pattern code expression.  The
2536       pattern code expression is like a regular code expression, except that
2537       the result of the code evaluation is treated as a regular expression
2538       and matched immediately.  A simple example is
2539
2540           $length = 5;
2541           $char = 'a';
2542           $x = 'aaaaabb';
2543           $x =~ /(??{$char x $length})/x; # matches, there are 5 of 'a'
2544
2545       This final example contains both ordinary and pattern code expressions.
2546       It detects whether a binary string 1101010010001... has a Fibonacci
2547       spacing 0,1,1,2,3,5,...  of the '1''s:
2548
2549           $x = "1101010010001000001";
2550           $z0 = ''; $z1 = '0';   # initial conditions
2551           print "It is a Fibonacci sequence\n"
2552               if $x =~ /^1         # match an initial '1'
2553                           (?:
2554                              ((??{ $z0 })) # match some '0'
2555                              1             # and then a '1'
2556                              (?{ $z0 = $z1; $z1 .= $^N; })
2557                           )+   # repeat as needed
2558                         $      # that is all there is
2559                        /x;
2560           printf "Largest sequence matched was %d\n", length($z1)-length($z0);
2561
2562       Remember that $^N is set to whatever was matched by the last completed
2563       capture group. This prints
2564
2565           It is a Fibonacci sequence
2566           Largest sequence matched was 5
2567
2568       Ha! Try that with your garden variety regexp package...
2569
2570       Note that the variables $z0 and $z1 are not substituted when the regexp
2571       is compiled, as happens for ordinary variables outside a code
2572       expression.  Rather, the whole code block is parsed as perl code at the
2573       same time as perl is compiling the code containing the literal regexp
2574       pattern.
2575
2576       This regexp without the "/x" modifier is
2577
2578           /^1(?:((??{ $z0 }))1(?{ $z0 = $z1; $z1 .= $^N; }))+$/
2579
2580       which shows that spaces are still possible in the code parts.
2581       Nevertheless, when working with code and conditional expressions, the
2582       extended form of regexps is almost necessary in creating and debugging
2583       regexps.
2584
2585   Backtracking control verbs
2586       Perl 5.10 introduced a number of control verbs intended to provide
2587       detailed control over the backtracking process, by directly influencing
2588       the regexp engine and by providing monitoring techniques.  See "Special
2589       Backtracking Control Verbs" in perlre for a detailed description.
2590
2591       Below is just one example, illustrating the control verb "(*FAIL)",
2592       which may be abbreviated as "(*F)". If this is inserted in a regexp it
2593       will cause it to fail, just as it would at some mismatch between the
2594       pattern and the string. Processing of the regexp continues as it would
2595       after any "normal" failure, so that, for instance, the next position in
2596       the string or another alternative will be tried. As failing to match
2597       doesn't preserve capture groups or produce results, it may be necessary
2598       to use this in combination with embedded code.
2599
2600          %count = ();
2601          "supercalifragilisticexpialidocious" =~
2602              /([aeiou])(?{ $count{$1}++; })(*FAIL)/i;
2603          printf "%3d '%s'\n", $count{$_}, $_ for (sort keys %count);
2604
2605       The pattern begins with a class matching a subset of letters.  Whenever
2606       this matches, a statement like "$count{'a'}++;" is executed,
2607       incrementing the letter's counter. Then "(*FAIL)" does what it says,
2608       and the regexp engine proceeds according to the book: as long as the
2609       end of the string hasn't been reached, the position is advanced before
2610       looking for another vowel. Thus, match or no match makes no difference,
2611       and the regexp engine proceeds until the entire string has been
2612       inspected.  (It's remarkable that an alternative solution using
2613       something like
2614
2615          $count{lc($_)}++ for split('', "supercalifragilisticexpialidocious");
2616          printf "%3d '%s'\n", $count2{$_}, $_ for ( qw{ a e i o u } );
2617
2618       is considerably slower.)
2619
2620   Pragmas and debugging
2621       Speaking of debugging, there are several pragmas available to control
2622       and debug regexps in Perl.  We have already encountered one pragma in
2623       the previous section, "use re 'eval';", that allows variable
2624       interpolation and code expressions to coexist in a regexp.  The other
2625       pragmas are
2626
2627           use re 'taint';
2628           $tainted = <>;
2629           @parts = ($tainted =~ /(\w+)\s+(\w+)/; # @parts is now tainted
2630
2631       The "taint" pragma causes any substrings from a match with a tainted
2632       variable to be tainted as well.  This is not normally the case, as
2633       regexps are often used to extract the safe bits from a tainted
2634       variable.  Use "taint" when you are not extracting safe bits, but are
2635       performing some other processing.  Both "taint" and "eval" pragmas are
2636       lexically scoped, which means they are in effect only until the end of
2637       the block enclosing the pragmas.
2638
2639           use re '/m';  # or any other flags
2640           $multiline_string =~ /^foo/; # /m is implied
2641
2642       The "re '/flags'" pragma (introduced in Perl 5.14) turns on the given
2643       regular expression flags until the end of the lexical scope.  See
2644       "'/flags' mode" in re for more detail.
2645
2646           use re 'debug';
2647           /^(.*)$/s;       # output debugging info
2648
2649           use re 'debugcolor';
2650           /^(.*)$/s;       # output debugging info in living color
2651
2652       The global "debug" and "debugcolor" pragmas allow one to get detailed
2653       debugging info about regexp compilation and execution.  "debugcolor" is
2654       the same as debug, except the debugging information is displayed in
2655       color on terminals that can display termcap color sequences.  Here is
2656       example output:
2657
2658           % perl -e 'use re "debug"; "abc" =~ /a*b+c/;'
2659           Compiling REx 'a*b+c'
2660           size 9 first at 1
2661              1: STAR(4)
2662              2:   EXACT <a>(0)
2663              4: PLUS(7)
2664              5:   EXACT <b>(0)
2665              7: EXACT <c>(9)
2666              9: END(0)
2667           floating 'bc' at 0..2147483647 (checking floating) minlen 2
2668           Guessing start of match, REx 'a*b+c' against 'abc'...
2669           Found floating substr 'bc' at offset 1...
2670           Guessed: match at offset 0
2671           Matching REx 'a*b+c' against 'abc'
2672             Setting an EVAL scope, savestack=3
2673              0 <> <abc>           |  1:  STAR
2674                                    EXACT <a> can match 1 times out of 32767...
2675             Setting an EVAL scope, savestack=3
2676              1 <a> <bc>           |  4:    PLUS
2677                                    EXACT <b> can match 1 times out of 32767...
2678             Setting an EVAL scope, savestack=3
2679              2 <ab> <c>           |  7:      EXACT <c>
2680              3 <abc> <>           |  9:      END
2681           Match successful!
2682           Freeing REx: 'a*b+c'
2683
2684       If you have gotten this far into the tutorial, you can probably guess
2685       what the different parts of the debugging output tell you.  The first
2686       part
2687
2688           Compiling REx 'a*b+c'
2689           size 9 first at 1
2690              1: STAR(4)
2691              2:   EXACT <a>(0)
2692              4: PLUS(7)
2693              5:   EXACT <b>(0)
2694              7: EXACT <c>(9)
2695              9: END(0)
2696
2697       describes the compilation stage.  STAR(4) means that there is a starred
2698       object, in this case 'a', and if it matches, goto line 4, i.e.,
2699       PLUS(7).  The middle lines describe some heuristics and optimizations
2700       performed before a match:
2701
2702           floating 'bc' at 0..2147483647 (checking floating) minlen 2
2703           Guessing start of match, REx 'a*b+c' against 'abc'...
2704           Found floating substr 'bc' at offset 1...
2705           Guessed: match at offset 0
2706
2707       Then the match is executed and the remaining lines describe the
2708       process:
2709
2710           Matching REx 'a*b+c' against 'abc'
2711             Setting an EVAL scope, savestack=3
2712              0 <> <abc>           |  1:  STAR
2713                                    EXACT <a> can match 1 times out of 32767...
2714             Setting an EVAL scope, savestack=3
2715              1 <a> <bc>           |  4:    PLUS
2716                                    EXACT <b> can match 1 times out of 32767...
2717             Setting an EVAL scope, savestack=3
2718              2 <ab> <c>           |  7:      EXACT <c>
2719              3 <abc> <>           |  9:      END
2720           Match successful!
2721           Freeing REx: 'a*b+c'
2722
2723       Each step is of the form "n <x> <y>", with "<x>" the part of the string
2724       matched and "<y>" the part not yet matched.  The "|  1:  STAR" says
2725       that Perl is at line number 1 in the compilation list above.  See
2726       "Debugging Regular Expressions" in perldebguts for much more detail.
2727
2728       An alternative method of debugging regexps is to embed "print"
2729       statements within the regexp.  This provides a blow-by-blow account of
2730       the backtracking in an alternation:
2731
2732           "that this" =~ m@(?{print "Start at position ", pos, "\n";})
2733                            t(?{print "t1\n";})
2734                            h(?{print "h1\n";})
2735                            i(?{print "i1\n";})
2736                            s(?{print "s1\n";})
2737                                |
2738                            t(?{print "t2\n";})
2739                            h(?{print "h2\n";})
2740                            a(?{print "a2\n";})
2741                            t(?{print "t2\n";})
2742                            (?{print "Done at position ", pos, "\n";})
2743                           @x;
2744
2745       prints
2746
2747           Start at position 0
2748           t1
2749           h1
2750           t2
2751           h2
2752           a2
2753           t2
2754           Done at position 4
2755

SEE ALSO

2757       This is just a tutorial.  For the full story on Perl regular
2758       expressions, see the perlre regular expressions reference page.
2759
2760       For more information on the matching "m//" and substitution "s///"
2761       operators, see "Regexp Quote-Like Operators" in perlop.  For
2762       information on the "split" operation, see "split" in perlfunc.
2763
2764       For an excellent all-around resource on the care and feeding of regular
2765       expressions, see the book Mastering Regular Expressions by Jeffrey
2766       Friedl (published by O'Reilly, ISBN 1556592-257-3).
2767
2769       Copyright (c) 2000 Mark Kvale.  All rights reserved.  Now maintained by
2770       Perl porters.
2771
2772       This document may be distributed under the same terms as Perl itself.
2773
2774   Acknowledgments
2775       The inspiration for the stop codon DNA example came from the ZIP code
2776       example in chapter 7 of Mastering Regular Expressions.
2777
2778       The author would like to thank Jeff Pinyan, Andrew Johnson, Peter
2779       Haworth, Ronald J Kimball, and Joe Smith for all their helpful
2780       comments.
2781
2782
2783
2784perl v5.28.2                      2018-11-01                      PERLRETUT(1)
Impressum