source: for-distributions/trunk/bin/windows/perl/lib/Pod/perlfaq6.pod@ 14489

Last change on this file since 14489 was 14489, checked in by oranfry, 17 years ago

upgrading to perl 5.8

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