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