FAQ sync
[p5sagit/p5-mst-13.2.git] / pod / perlfaq6.pod
1 =head1 NAME
2
3 perlfaq6 - Regular Expressions ($Revision: 7910 $)
4
5 =head1 DESCRIPTION
6
7 This section is surprisingly small because the rest of the FAQ is
8 littered with answers involving regular expressions.  For example,
9 decoding a URL and checking whether something is a number are handled
10 with regular expressions, but those answers are found elsewhere in
11 this document (in L<perlfaq9>: "How do I decode or create those %-encodings
12 on the web" and L<perlfaq4>: "How do I determine whether a scalar is
13 a number/whole/integer/float", to be precise).
14
15 =head2 How can I hope to use regular expressions without creating illegible and unmaintainable code?
16 X<regex, legibility> X<regexp, legibility>
17 X<regular expression, legibility> X</x>
18
19 Three techniques can make regular expressions maintainable and
20 understandable.
21
22 =over 4
23
24 =item Comments Outside the Regex
25
26 Describe what you're doing and how you're doing it, using normal Perl
27 comments.
28
29         # turn the line into the first word, a colon, and the
30         # number of characters on the rest of the line
31         s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
32
33 =item Comments Inside the Regex
34
35 The C</x> modifier causes whitespace to be ignored in a regex pattern
36 (except in a character class), and also allows you to use normal
37 comments there, too.  As you can imagine, whitespace and comments help
38 a lot.
39
40 C</x> lets you turn this:
41
42         s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
43
44 into this:
45
46         s{ <                    # opening angle bracket
47                 (?:                 # Non-backreffing grouping paren
48                         [^>'"] *        # 0 or more things that are neither > nor ' nor "
49                                 |           #    or else
50                         ".*?"           # a section between double quotes (stingy match)
51                                 |           #    or else
52                         '.*?'           # a section between single quotes (stingy match)
53                 ) +                 #   all occurring one or more times
54                 >                   # closing angle bracket
55         }{}gsx;                 # replace with nothing, i.e. delete
56
57 It's still not quite so clear as prose, but it is very useful for
58 describing the meaning of each part of the pattern.
59
60 =item Different Delimiters
61
62 While we normally think of patterns as being delimited with C</>
63 characters, they can be delimited by almost any character.  L<perlre>
64 describes this.  For example, the C<s///> above uses braces as
65 delimiters.  Selecting another delimiter can avoid quoting the
66 delimiter within the pattern:
67
68         s/\/usr\/local/\/usr\/share/g;  # bad delimiter choice
69         s#/usr/local#/usr/share#g;              # better
70
71 =back
72
73 =head2 I'm having trouble matching over more than one line.  What's wrong?
74 X<regex, multiline> X<regexp, multiline> X<regular expression, multiline>
75
76 Either you don't have more than one line in the string you're looking
77 at (probably), or else you aren't using the correct modifier(s) on
78 your pattern (possibly).
79
80 There are many ways to get multiline data into a string.  If you want
81 it to happen automatically while reading input, you'll want to set $/
82 (probably to '' for paragraphs or C<undef> for the whole file) to
83 allow you to read more than one line at a time.
84
85 Read L<perlre> to help you decide which of C</s> and C</m> (or both)
86 you might want to use: C</s> allows dot to include newline, and C</m>
87 allows caret and dollar to match next to a newline, not just at the
88 end of the string.  You do need to make sure that you've actually
89 got a multiline string in there.
90
91 For example, this program detects duplicate words, even when they span
92 line breaks (but not paragraph ones).  For this example, we don't need
93 C</s> because we aren't using dot in a regular expression that we want
94 to cross line boundaries.  Neither do we need C</m> because we aren't
95 wanting caret or dollar to match at any point inside the record next
96 to newlines.  But it's imperative that $/ be set to something other
97 than the default, or else we won't actually ever have a multiline
98 record read in.
99
100         $/ = '';                # read in more whole paragraph, not just one line
101         while ( <> ) {
102                 while ( /\b([\w'-]+)(\s+\1)+\b/gi ) {   # word starts alpha
103                         print "Duplicate $1 at paragraph $.\n";
104                 }
105         }
106
107 Here's code that finds sentences that begin with "From " (which would
108 be mangled by many mailers):
109
110         $/ = '';                # read in more whole paragraph, not just one line
111         while ( <> ) {
112                 while ( /^From /gm ) { # /m makes ^ match next to \n
113                 print "leading from in paragraph $.\n";
114                 }
115         }
116
117 Here's code that finds everything between START and END in a paragraph:
118
119         undef $/;               # read in whole file, not just one line or paragraph
120         while ( <> ) {
121                 while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
122                     print "$1\n";
123                 }
124         }
125
126 =head2 How can I pull out lines between two patterns that are themselves on different lines?
127 X<..>
128
129 You can use Perl's somewhat exotic C<..> operator (documented in
130 L<perlop>):
131
132         perl -ne 'print if /START/ .. /END/' file1 file2 ...
133
134 If you wanted text and not lines, you would use
135
136         perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
137
138 But if you want nested occurrences of C<START> through C<END>, you'll
139 run up against the problem described in the question in this section
140 on matching balanced text.
141
142 Here's another example of using C<..>:
143
144         while (<>) {
145                 $in_header =   1  .. /^$/;
146                 $in_body   = /^$/ .. eof;
147         # now choose between them
148         } continue {
149                 $. = 0 if eof;  # fix $.
150         }
151
152 =head2 I put a regular expression into $/ but it didn't work. What's wrong?
153 X<$/, regexes in> X<$INPUT_RECORD_SEPARATOR, regexes in>
154 X<$RS, regexes in>
155
156 Up to Perl 5.8.0, $/ has to be a string.  This may change in 5.10,
157 but don't get your hopes up. Until then, you can use these examples
158 if you really need to do this.
159
160 If you have File::Stream, this is easy.
161
162         use File::Stream;
163
164         my $stream = File::Stream->new(
165                 $filehandle,
166                 separator => qr/\s*,\s*/,
167                 );
168
169         print "$_\n" while <$stream>;
170
171 If you don't have File::Stream, you have to do a little more work.
172
173 You can use the four argument form of sysread to continually add to
174 a buffer.  After you add to the buffer, you check if you have a
175 complete line (using your regular expression).
176
177         local $_ = "";
178         while( sysread FH, $_, 8192, length ) {
179                 while( s/^((?s).*?)your_pattern/ ) {
180                         my $record = $1;
181                         # do stuff here.
182                 }
183         }
184
185  You can do the same thing with foreach and a match using the
186  c flag and the \G anchor, if you do not mind your entire file
187  being in memory at the end.
188
189         local $_ = "";
190         while( sysread FH, $_, 8192, length ) {
191                 foreach my $record ( m/\G((?s).*?)your_pattern/gc ) {
192                         # do stuff here.
193                 }
194         substr( $_, 0, pos ) = "" if pos;
195         }
196
197
198 =head2 How do I substitute case insensitively on the LHS while preserving case on the RHS?
199 X<replace, case preserving> X<substitute, case preserving>
200 X<substitution, case preserving> X<s, case preserving>
201
202 Here's a lovely Perlish solution by Larry Rosler.  It exploits
203 properties of bitwise xor on ASCII strings.
204
205         $_= "this is a TEsT case";
206
207         $old = 'test';
208         $new = 'success';
209
210         s{(\Q$old\E)}
211         { uc $new | (uc $1 ^ $1) .
212                 (uc(substr $1, -1) ^ substr $1, -1) x
213                 (length($new) - length $1)
214         }egi;
215
216         print;
217
218 And here it is as a subroutine, modeled after the above:
219
220         sub preserve_case($$) {
221                 my ($old, $new) = @_;
222                 my $mask = uc $old ^ $old;
223
224                 uc $new | $mask .
225                         substr($mask, -1) x (length($new) - length($old))
226     }
227
228         $a = "this is a TEsT case";
229         $a =~ s/(test)/preserve_case($1, "success")/egi;
230         print "$a\n";
231
232 This prints:
233
234         this is a SUcCESS case
235
236 As an alternative, to keep the case of the replacement word if it is
237 longer than the original, you can use this code, by Jeff Pinyan:
238
239         sub preserve_case {
240                 my ($from, $to) = @_;
241                 my ($lf, $lt) = map length, @_;
242
243                 if ($lt < $lf) { $from = substr $from, 0, $lt }
244                 else { $from .= substr $to, $lf }
245
246                 return uc $to | ($from ^ uc $from);
247                 }
248
249 This changes the sentence to "this is a SUcCess case."
250
251 Just to show that C programmers can write C in any programming language,
252 if you prefer a more C-like solution, the following script makes the
253 substitution have the same case, letter by letter, as the original.
254 (It also happens to run about 240% slower than the Perlish solution runs.)
255 If the substitution has more characters than the string being substituted,
256 the case of the last character is used for the rest of the substitution.
257
258         # Original by Nathan Torkington, massaged by Jeffrey Friedl
259         #
260         sub preserve_case($$)
261         {
262                 my ($old, $new) = @_;
263                 my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
264                 my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
265                 my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
266
267                 for ($i = 0; $i < $len; $i++) {
268                         if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
269                                 $state = 0;
270                         } elsif (lc $c eq $c) {
271                                 substr($new, $i, 1) = lc(substr($new, $i, 1));
272                                 $state = 1;
273                         } else {
274                                 substr($new, $i, 1) = uc(substr($new, $i, 1));
275                                 $state = 2;
276                         }
277                 }
278                 # finish up with any remaining new (for when new is longer than old)
279                 if ($newlen > $oldlen) {
280                         if ($state == 1) {
281                                 substr($new, $oldlen) = lc(substr($new, $oldlen));
282                         } elsif ($state == 2) {
283                                 substr($new, $oldlen) = uc(substr($new, $oldlen));
284                         }
285                 }
286                 return $new;
287         }
288
289 =head2 How can I make C<\w> match national character sets?
290 X<\w>
291
292 Put C<use locale;> in your script.  The \w character class is taken
293 from the current locale.
294
295 See L<perllocale> for details.
296
297 =head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
298 X<alpha>
299
300 You can use the POSIX character class syntax C</[[:alpha:]]/>
301 documented in L<perlre>.
302
303 No matter which locale you are in, the alphabetic characters are
304 the characters in \w without the digits and the underscore.
305 As a regex, that looks like C</[^\W\d_]/>.  Its complement,
306 the non-alphabetics, is then everything in \W along with
307 the digits and the underscore, or C</[\W\d_]/>.
308
309 =head2 How can I quote a variable to use in a regex?
310 X<regex, escaping> X<regexp, escaping> X<regular expression, escaping>
311
312 The Perl parser will expand $variable and @variable references in
313 regular expressions unless the delimiter is a single quote.  Remember,
314 too, that the right-hand side of a C<s///> substitution is considered
315 a double-quoted string (see L<perlop> for more details).  Remember
316 also that any regex special characters will be acted on unless you
317 precede the substitution with \Q.  Here's an example:
318
319         $string = "Placido P. Octopus";
320         $regex  = "P.";
321
322         $string =~ s/$regex/Polyp/;
323         # $string is now "Polypacido P. Octopus"
324
325 Because C<.> is special in regular expressions, and can match any
326 single character, the regex C<P.> here has matched the <Pl> in the
327 original string.
328
329 To escape the special meaning of C<.>, we use C<\Q>:
330
331         $string = "Placido P. Octopus";
332         $regex  = "P.";
333
334         $string =~ s/\Q$regex/Polyp/;
335         # $string is now "Placido Polyp Octopus"
336
337 The use of C<\Q> causes the <.> in the regex to be treated as a
338 regular character, so that C<P.> matches a C<P> followed by a dot.
339
340 =head2 What is C</o> really for?
341 X</o>
342
343 Using a variable in a regular expression match forces a re-evaluation
344 (and perhaps recompilation) each time the regular expression is
345 encountered.  The C</o> modifier locks in the regex the first time
346 it's used.  This always happens in a constant regular expression, and
347 in fact, the pattern was compiled into the internal format at the same
348 time your entire program was.
349
350 Use of C</o> is irrelevant unless variable interpolation is used in
351 the pattern, and if so, the regex engine will neither know nor care
352 whether the variables change after the pattern is evaluated the I<very
353 first> time.
354
355 C</o> is often used to gain an extra measure of efficiency by not
356 performing subsequent evaluations when you know it won't matter
357 (because you know the variables won't change), or more rarely, when
358 you don't want the regex to notice if they do.
359
360 For example, here's a "paragrep" program:
361
362         $/ = '';  # paragraph mode
363         $pat = shift;
364         while (<>) {
365                 print if /$pat/o;
366         }
367
368 =head2 How do I use a regular expression to strip C style comments from a file?
369
370 While this actually can be done, it's much harder than you'd think.
371 For example, this one-liner
372
373         perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
374
375 will work in many but not all cases.  You see, it's too simple-minded for
376 certain kinds of C programs, in particular, those with what appear to be
377 comments in quoted strings.  For that, you'd need something like this,
378 created by Jeffrey Friedl and later modified by Fred Curtis.
379
380         $/ = undef;
381         $_ = <>;
382         s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
383         print;
384
385 This could, of course, be more legibly written with the C</x> modifier, adding
386 whitespace and comments.  Here it is expanded, courtesy of Fred Curtis.
387
388     s{
389        /\*         ##  Start of /* ... */ comment
390        [^*]*\*+    ##  Non-* followed by 1-or-more *'s
391        (
392          [^/*][^*]*\*+
393        )*          ##  0-or-more things which don't start with /
394                    ##    but do end with '*'
395        /           ##  End of /* ... */ comment
396
397      |         ##     OR  various things which aren't comments:
398
399        (
400          "           ##  Start of " ... " string
401          (
402            \\.           ##  Escaped char
403          |               ##    OR
404            [^"\\]        ##  Non "\
405          )*
406          "           ##  End of " ... " string
407
408        |         ##     OR
409
410          '           ##  Start of ' ... ' string
411          (
412            \\.           ##  Escaped char
413          |               ##    OR
414            [^'\\]        ##  Non '\
415          )*
416          '           ##  End of ' ... ' string
417
418        |         ##     OR
419
420          .           ##  Anything other char
421          [^/"'\\]*   ##  Chars which doesn't start a comment, string or escape
422        )
423      }{defined $2 ? $2 : ""}gxse;
424
425 A slight modification also removes C++ comments, as long as they are not
426 spread over multiple lines using a continuation character):
427
428         s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse;
429
430 =head2 Can I use Perl regular expressions to match balanced text?
431 X<regex, matching balanced test> X<regexp, matching balanced test>
432 X<regular expression, matching balanced test>
433
434 Historically, Perl regular expressions were not capable of matching
435 balanced text.  As of more recent versions of perl including 5.6.1
436 experimental features have been added that make it possible to do this.
437 Look at the documentation for the (??{ }) construct in recent perlre manual
438 pages to see an example of matching balanced parentheses.  Be sure to take
439 special notice of the  warnings present in the manual before making use
440 of this feature.
441
442 CPAN contains many modules that can be useful for matching text
443 depending on the context.  Damian Conway provides some useful
444 patterns in Regexp::Common.  The module Text::Balanced provides a
445 general solution to this problem.
446
447 One of the common applications of balanced text matching is working
448 with XML and HTML.  There are many modules available that support
449 these needs.  Two examples are HTML::Parser and XML::Parser. There
450 are many others.
451
452 An elaborate subroutine (for 7-bit ASCII only) to pull out balanced
453 and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,
454 or C<(> and C<)> can be found in
455 http://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz .
456
457 The C::Scan module from CPAN also contains such subs for internal use,
458 but they are undocumented.
459
460 =head2 What does it mean that regexes are greedy?  How can I get around it?
461 X<greedy> X<greediness>
462
463 Most people mean that greedy regexes match as much as they can.
464 Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
465 C<{}>) that are greedy rather than the whole pattern; Perl prefers local
466 greed and immediate gratification to overall greed.  To get non-greedy
467 versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
468
469 An example:
470
471         $s1 = $s2 = "I am very very cold";
472         $s1 =~ s/ve.*y //;      # I am cold
473         $s2 =~ s/ve.*?y //;     # I am very cold
474
475 Notice how the second substitution stopped matching as soon as it
476 encountered "y ".  The C<*?> quantifier effectively tells the regular
477 expression engine to find a match as quickly as possible and pass
478 control on to whatever is next in line, like you would if you were
479 playing hot potato.
480
481 =head2 How do I process each word on each line?
482 X<word>
483
484 Use the split function:
485
486         while (<>) {
487                 foreach $word ( split ) {
488                         # do something with $word here
489                 }
490         }
491
492 Note that this isn't really a word in the English sense; it's just
493 chunks of consecutive non-whitespace characters.
494
495 To work with only alphanumeric sequences (including underscores), you
496 might consider
497
498         while (<>) {
499                 foreach $word (m/(\w+)/g) {
500                         # do something with $word here
501                 }
502         }
503
504 =head2 How can I print out a word-frequency or line-frequency summary?
505
506 To do this, you have to parse out each word in the input stream.  We'll
507 pretend that by word you mean chunk of alphabetics, hyphens, or
508 apostrophes, rather than the non-whitespace chunk idea of a word given
509 in the previous question:
510
511         while (<>) {
512                 while ( /(\b[^\W_\d][\w'-]+\b)/g ) {   # misses "`sheep'"
513                         $seen{$1}++;
514                 }
515         }
516
517         while ( ($word, $count) = each %seen ) {
518                 print "$count $word\n";
519                 }
520
521 If you wanted to do the same thing for lines, you wouldn't need a
522 regular expression:
523
524         while (<>) {
525                 $seen{$_}++;
526                 }
527
528         while ( ($line, $count) = each %seen ) {
529                 print "$count $line";
530         }
531
532 If you want these output in a sorted order, see L<perlfaq4>: "How do I
533 sort a hash (optionally by value instead of key)?".
534
535 =head2 How can I do approximate matching?
536 X<match, approximate> X<matching, approximate>
537
538 See the module String::Approx available from CPAN.
539
540 =head2 How do I efficiently match many regular expressions at once?
541 X<regex, efficiency> X<regexp, efficiency>
542 X<regular expression, efficiency>
543
544 ( contributed by brian d foy )
545
546 Avoid asking Perl to compile a regular expression every time
547 you want to match it.  In this example, perl must recompile
548 the regular expression for every iteration of the foreach()
549 loop since it has no way to know what $pattern will be.
550
551         @patterns = qw( foo bar baz );
552
553         LINE: while( <DATA> )
554                 {
555                 foreach $pattern ( @patterns )
556                         {
557                         if( /\b$pattern\b/i )
558                                 {
559                                 print;
560                                 next LINE;
561                                 }
562                         }
563                 }
564
565 The qr// operator showed up in perl 5.005.  It compiles a
566 regular expression, but doesn't apply it.  When you use the
567 pre-compiled version of the regex, perl does less work. In
568 this example, I inserted a map() to turn each pattern into
569 its pre-compiled form.  The rest of the script is the same,
570 but faster.
571
572         @patterns = map { qr/\b$_\b/i } qw( foo bar baz );
573
574         LINE: while( <> )
575                 {
576                 foreach $pattern ( @patterns )
577                         {
578                         print if /\b$pattern\b/i;
579                         next LINE;
580                         }
581                 }
582
583 In some cases, you may be able to make several patterns into
584 a single regular expression.  Beware of situations that require
585 backtracking though.
586
587         $regex = join '|', qw( foo bar baz );
588
589         LINE: while( <> )
590                 {
591                 print if /\b(?:$regex)\b/i;
592                 }
593
594 For more details on regular expression efficiency, see Mastering
595 Regular Expressions by Jeffrey Freidl.  He explains how regular
596 expressions engine work and why some patterns are surprisingly
597 inefficient.  Once you understand how perl applies regular
598 expressions, you can tune them for individual situations.
599
600 =head2 Why don't word-boundary searches with C<\b> work for me?
601 X<\b>
602
603 (contributed by brian d foy)
604
605 Ensure that you know what \b really does: it's the boundary between a
606 word character, \w, and something that isn't a word character. That
607 thing that isn't a word character might be \W, but it can also be the
608 start or end of the string.
609
610 It's not (not!) the boundary between whitespace and non-whitespace,
611 and it's not the stuff between words we use to create sentences.
612
613 In regex speak, a word boundary (\b) is a "zero width assertion",
614 meaning that it doesn't represent a character in the string, but a
615 condition at a certain position.
616
617 For the regular expression, /\bPerl\b/, there has to be a word
618 boundary before the "P" and after the "l".  As long as something other
619 than a word character precedes the "P" and succeeds the "l", the
620 pattern will match. These strings match /\bPerl\b/.
621
622         "Perl"    # no word char before P or after l
623         "Perl "   # same as previous (space is not a word char)
624         "'Perl'"  # the ' char is not a word char
625         "Perl's"  # no word char before P, non-word char after "l"
626
627 These strings do not match /\bPerl\b/.
628
629         "Perl_"   # _ is a word char!
630         "Perler"  # no word char before P, but one after l
631
632 You don't have to use \b to match words though.  You can look for
633 non-word characters surrounded by word characters.  These strings
634 match the pattern /\b'\b/.
635
636         "don't"   # the ' char is surrounded by "n" and "t"
637         "qep'a'"  # the ' char is surrounded by "p" and "a"
638
639 These strings do not match /\b'\b/.
640
641         "foo'"    # there is no word char after non-word '
642
643 You can also use the complement of \b, \B, to specify that there
644 should not be a word boundary.
645
646 In the pattern /\Bam\B/, there must be a word character before the "a"
647 and after the "m". These patterns match /\Bam\B/:
648
649         "llama"   # "am" surrounded by word chars
650         "Samuel"  # same
651
652 These strings do not match /\Bam\B/
653
654         "Sam"      # no word boundary before "a", but one after "m"
655         "I am Sam" # "am" surrounded by non-word chars
656
657
658 =head2 Why does using $&, $`, or $' slow my program down?
659 X<$MATCH> X<$&> X<$POSTMATCH> X<$'> X<$PREMATCH> X<$`>
660
661 (contributed by Anno Siegel)
662
663 Once Perl sees that you need one of these variables anywhere in the
664 program, it provides them on each and every pattern match. That means
665 that on every pattern match the entire string will be copied, part of it
666 to $`, part to $&, and part to $'. Thus the penalty is most severe with
667 long strings and patterns that match often. Avoid $&, $', and $` if you
668 can, but if you can't, once you've used them at all, use them at will
669 because you've already paid the price. Remember that some algorithms
670 really appreciate them. As of the 5.005 release, the $& variable is no
671 longer "expensive" the way the other two are.
672
673 Since Perl 5.6.1 the special variables @- and @+ can functionally replace
674 $`, $& and $'.  These arrays contain pointers to the beginning and end
675 of each match (see perlvar for the full story), so they give you
676 essentially the same information, but without the risk of excessive
677 string copying.
678
679 =head2 What good is C<\G> in a regular expression?
680 X<\G>
681
682 You use the C<\G> anchor to start the next match on the same
683 string where the last match left off.  The regular
684 expression engine cannot skip over any characters to find
685 the next match with this anchor, so C<\G> is similar to the
686 beginning of string anchor, C<^>.  The C<\G> anchor is typically
687 used with the C<g> flag.  It uses the value of pos()
688 as the position to start the next match.  As the match
689 operator makes successive matches, it updates pos() with the
690 position of the next character past the last match (or the
691 first character of the next match, depending on how you like
692 to look at it). Each string has its own pos() value.
693
694 Suppose you want to match all of consective pairs of digits
695 in a string like "1122a44" and stop matching when you
696 encounter non-digits.  You want to match C<11> and C<22> but
697 the letter <a> shows up between C<22> and C<44> and you want
698 to stop at C<a>. Simply matching pairs of digits skips over
699 the C<a> and still matches C<44>.
700
701         $_ = "1122a44";
702         my @pairs = m/(\d\d)/g;   # qw( 11 22 44 )
703
704 If you use the \G anchor, you force the match after C<22> to
705 start with the C<a>.  The regular expression cannot match
706 there since it does not find a digit, so the next match
707 fails and the match operator returns the pairs it already
708 found.
709
710         $_ = "1122a44";
711         my @pairs = m/\G(\d\d)/g; # qw( 11 22 )
712
713 You can also use the C<\G> anchor in scalar context. You
714 still need the C<g> flag.
715
716         $_ = "1122a44";
717         while( m/\G(\d\d)/g )
718                 {
719                 print "Found $1\n";
720                 }
721
722 After the match fails at the letter C<a>, perl resets pos()
723 and the next match on the same string starts at the beginning.
724
725         $_ = "1122a44";
726         while( m/\G(\d\d)/g )
727                 {
728                 print "Found $1\n";
729                 }
730
731         print "Found $1 after while" if m/(\d\d)/g; # finds "11"
732
733 You can disable pos() resets on fail with the C<c> flag.
734 Subsequent matches start where the last successful match
735 ended (the value of pos()) even if a match on the same
736 string as failed in the meantime. In this case, the match
737 after the while() loop starts at the C<a> (where the last
738 match stopped), and since it does not use any anchor it can
739 skip over the C<a> to find "44".
740
741         $_ = "1122a44";
742         while( m/\G(\d\d)/gc )
743                 {
744                 print "Found $1\n";
745                 }
746
747         print "Found $1 after while" if m/(\d\d)/g; # finds "44"
748
749 Typically you use the C<\G> anchor with the C<c> flag
750 when you want to try a different match if one fails,
751 such as in a tokenizer. Jeffrey Friedl offers this example
752 which works in 5.004 or later.
753
754         while (<>) {
755                 chomp;
756                 PARSER: {
757                         m/ \G( \d+\b    )/gcx   && do { print "number: $1\n";  redo; };
758                         m/ \G( \w+      )/gcx   && do { print "word:   $1\n";  redo; };
759                         m/ \G( \s+      )/gcx   && do { print "space:  $1\n";  redo; };
760                         m/ \G( [^\w\d]+ )/gcx   && do { print "other:  $1\n";  redo; };
761                 }
762         }
763
764 For each line, the PARSER loop first tries to match a series
765 of digits followed by a word boundary.  This match has to
766 start at the place the last match left off (or the beginning
767 of the string on the first match). Since C<m/ \G( \d+\b
768 )/gcx> uses the C<c> flag, if the string does not match that
769 regular expression, perl does not reset pos() and the next
770 match starts at the same position to try a different
771 pattern.
772
773 =head2 Are Perl regexes DFAs or NFAs?  Are they POSIX compliant?
774 X<DFA> X<NFA> X<POSIX>
775
776 While it's true that Perl's regular expressions resemble the DFAs
777 (deterministic finite automata) of the egrep(1) program, they are in
778 fact implemented as NFAs (non-deterministic finite automata) to allow
779 backtracking and backreferencing.  And they aren't POSIX-style either,
780 because those guarantee worst-case behavior for all cases.  (It seems
781 that some people prefer guarantees of consistency, even when what's
782 guaranteed is slowness.)  See the book "Mastering Regular Expressions"
783 (from O'Reilly) by Jeffrey Friedl for all the details you could ever
784 hope to know on these matters (a full citation appears in
785 L<perlfaq2>).
786
787 =head2 What's wrong with using grep in a void context?
788 X<grep>
789
790 The problem is that grep builds a return list, regardless of the context.
791 This means you're making Perl go to the trouble of building a list that
792 you then just throw away. If the list is large, you waste both time and space.
793 If your intent is to iterate over the list, then use a for loop for this
794 purpose.
795
796 In perls older than 5.8.1, map suffers from this problem as well.
797 But since 5.8.1, this has been fixed, and map is context aware - in void
798 context, no lists are constructed.
799
800 =head2 How can I match strings with multibyte characters?
801 X<regex, and multibyte characters> X<regexp, and multibyte characters>
802 X<regular expression, and multibyte characters> X<martian> X<encoding, Martian>
803
804 Starting from Perl 5.6 Perl has had some level of multibyte character
805 support.  Perl 5.8 or later is recommended.  Supported multibyte
806 character repertoires include Unicode, and legacy encodings
807 through the Encode module.  See L<perluniintro>, L<perlunicode>,
808 and L<Encode>.
809
810 If you are stuck with older Perls, you can do Unicode with the
811 C<Unicode::String> module, and character conversions using the
812 C<Unicode::Map8> and C<Unicode::Map> modules.  If you are using
813 Japanese encodings, you might try using the jperl 5.005_03.
814
815 Finally, the following set of approaches was offered by Jeffrey
816 Friedl, whose article in issue #5 of The Perl Journal talks about
817 this very matter.
818
819 Let's suppose you have some weird Martian encoding where pairs of
820 ASCII uppercase letters encode single Martian letters (i.e. the two
821 bytes "CV" make a single Martian letter, as do the two bytes "SG",
822 "VS", "XX", etc.). Other bytes represent single characters, just like
823 ASCII.
824
825 So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
826 nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
827
828 Now, say you want to search for the single character C</GX/>. Perl
829 doesn't know about Martian, so it'll find the two bytes "GX" in the "I
830 am CVSGXX!"  string, even though that character isn't there: it just
831 looks like it is because "SG" is next to "XX", but there's no real
832 "GX".  This is a big problem.
833
834 Here are a few ways, all painful, to deal with it:
835
836         # Make sure adjacent "martian" bytes are no longer adjacent.
837         $martian =~ s/([A-Z][A-Z])/ $1 /g;
838
839         print "found GX!\n" if $martian =~ /GX/;
840
841 Or like this:
842
843         @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
844         # above is conceptually similar to:     @chars = $text =~ m/(.)/g;
845         #
846         foreach $char (@chars) {
847         print "found GX!\n", last if $char eq 'GX';
848         }
849
850 Or like this:
851
852         while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) {  # \G probably unneeded
853                 print "found GX!\n", last if $1 eq 'GX';
854                 }
855
856 Here's another, slightly less painful, way to do it from Benjamin
857 Goldberg, who uses a zero-width negative look-behind assertion.
858
859         print "found GX!\n" if  $martian =~ m/
860                 (?<![A-Z])
861                 (?:[A-Z][A-Z])*?
862                 GX
863                 /x;
864
865 This succeeds if the "martian" character GX is in the string, and fails
866 otherwise.  If you don't like using (?<!), a zero-width negative
867 look-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]).
868
869 It does have the drawback of putting the wrong thing in $-[0] and $+[0],
870 but this usually can be worked around.
871
872 =head2 How do I match a regular expression that's in a variable?
873 X<regex, in variable> X<eval> X<regex> X<quotemeta> X<\Q, regex>
874 X<\E, regex>, X<qr//>
875
876 (contributed by brian d foy)
877
878 We don't have to hard-code patterns into the match operator (or
879 anything else that works with regular expressions). We can put the
880 pattern in a variable for later use.
881
882 The match operator is a double quote context, so you can interpolate
883 your variable just like a double quoted string. In this case, you
884 read the regular expression as user input and store it in C<$regex>.
885 Once you have the pattern in C<$regex>, you use that variable in the
886 match operator.
887
888         chomp( my $regex = <STDIN> );
889
890         if( $string =~ m/$regex/ ) { ... }
891
892 Any regular expression special characters in C<$regex> are still
893 special, and the pattern still has to be valid or Perl will complain.
894 For instance, in this pattern there is an unpaired parenthesis.
895
896         my $regex = "Unmatched ( paren";
897
898         "Two parens to bind them all" =~ m/$regex/;
899
900 When Perl compiles the regular expression, it treats the parenthesis
901 as the start of a memory match. When it doesn't find the closing
902 parenthesis, it complains:
903
904         Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE  paren/ at script line 3.
905
906 You can get around this in several ways depending on our situation.
907 First, if you don't want any of the characters in the string to be
908 special, you can escape them with C<quotemeta> before you use the string.
909
910         chomp( my $regex = <STDIN> );
911         $regex = quotemeta( $regex );
912
913         if( $string =~ m/$regex/ ) { ... }
914
915 You can also do this directly in the match operator using the C<\Q>
916 and C<\E> sequences. The C<\Q> tells Perl where to start escaping
917 special characters, and the C<\E> tells it where to stop (see L<perlop>
918 for more details).
919
920         chomp( my $regex = <STDIN> );
921
922         if( $string =~ m/\Q$regex\E/ ) { ... }
923
924 Alternately, you can use C<qr//>, the regular expression quote operator (see
925 L<perlop> for more details).  It quotes and perhaps compiles the pattern,
926 and you can apply regular expression flags to the pattern.
927
928         chomp( my $input = <STDIN> );
929
930         my $regex = qr/$input/is;
931
932         $string =~ m/$regex/  # same as m/$input/is;
933
934 You might also want to trap any errors by wrapping an C<eval> block
935 around the whole thing.
936
937         chomp( my $input = <STDIN> );
938
939         eval {
940                 if( $string =~ m/\Q$input\E/ ) { ... }
941                 };
942         warn $@ if $@;
943
944 Or...
945
946         my $regex = eval { qr/$input/is };
947         if( defined $regex ) {
948                 $string =~ m/$regex/;
949                 }
950         else {
951                 warn $@;
952                 }
953
954 =head1 REVISION
955
956 Revision: $Revision: 7910 $
957
958 Date: $Date: 2006-10-07 22:38:54 +0200 (sam, 07 oct 2006) $
959
960 See L<perlfaq> for source control details and availability.
961
962 =head1 AUTHOR AND COPYRIGHT
963
964 Copyright (c) 1997-2006 Tom Christiansen, Nathan Torkington, and
965 other authors as noted. All rights reserved.
966
967 This documentation is free; you can redistribute it and/or modify it
968 under the same terms as Perl itself.
969
970 Irrespective of its distribution, all code examples in this file
971 are hereby placed into the public domain.  You are permitted and
972 encouraged to use this code in your own programs for fun
973 or for profit as you see fit.  A simple comment in the code giving
974 credit would be courteous but is not required.