home *** CD-ROM | disk | FTP | other *** search
/ Australian Personal Computer 2004 July / APC0407D2.iso / workshop / apache / files / ActivePerl-5.6.1.638-MSWin32-x86.msi / _a3c8753852bf31c103b8bd822bb3272f < prev    next >
Encoding:
Text File  |  2004-04-13  |  25.2 KB  |  712 lines

  1. =head1 NAME
  2.  
  3. perlfaq6 - Regexes ($Revision: 1.27 $, $Date: 1999/05/23 16:08:30 $)
  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<perfaq4>: ``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.  
  17. Three techniques can make regular expressions maintainable and
  18. understandable.
  19.  
  20. =over 4
  21.  
  22. =item Comments Outside the Regex
  23.  
  24. Describe what you're doing and how you're doing it, using normal Perl
  25. comments.
  26.  
  27.     # turn the line into the first word, a colon, and the
  28.     # number of characters on the rest of the line
  29.     s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg;
  30.  
  31. =item Comments Inside the Regex
  32.  
  33. The C</x> modifier causes whitespace to be ignored in a regex pattern
  34. (except in a character class), and also allows you to use normal
  35. comments there, too.  As you can imagine, whitespace and comments help
  36. a lot.
  37.  
  38. C</x> lets you turn this:
  39.  
  40.     s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
  41.  
  42. into 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.  
  55. It's still not quite so clear as prose, but it is very useful for
  56. describing the meaning of each part of the pattern.
  57.  
  58. =item Different Delimiters
  59.  
  60. While we normally think of patterns as being delimited with C</>
  61. characters, they can be delimited by almost any character.  L<perlre>
  62. describes this.  For example, the C<s///> above uses braces as
  63. delimiters.  Selecting another delimiter can avoid quoting the
  64. delimiter 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.  
  73. Either you don't have more than one line in the string you're looking at
  74. (probably), or else you aren't using the correct modifier(s) on your
  75. pattern (possibly).
  76.  
  77. There are many ways to get multiline data into a string.  If you want
  78. it to happen automatically while reading input, you'll want to set $/
  79. (probably to '' for paragraphs or C<undef> for the whole file) to
  80. allow you to read more than one line at a time.
  81.  
  82. Read L<perlre> to help you decide which of C</s> and C</m> (or both)
  83. you might want to use: C</s> allows dot to include newline, and C</m>
  84. allows caret and dollar to match next to a newline, not just at the
  85. end of the string.  You do need to make sure that you've actually
  86. got a multiline string in there.
  87.  
  88. For example, this program detects duplicate words, even when they span
  89. line breaks (but not paragraph ones).  For this example, we don't need
  90. C</s> because we aren't using dot in a regular expression that we want
  91. to cross line boundaries.  Neither do we need C</m> because we aren't
  92. wanting caret or dollar to match at any point inside the record next
  93. to newlines.  But it's imperative that $/ be set to something other
  94. than the default, or else we won't actually ever have a multiline
  95. record read in.
  96.  
  97.     $/ = '';          # read in more whole paragraph, not just one line
  98.     while ( <> ) {
  99.     while ( /\b([\w'-]+)(\s+\1)+\b/gi ) {      # word starts alpha
  100.         print "Duplicate $1 at paragraph $.\n";
  101.     }
  102.     }
  103.  
  104. Here's code that finds sentences that begin with "From " (which would
  105. be 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.  
  114. Here'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 ( <> ) {
  118.     while ( /START(.*?)END/sm ) { # /s makes . cross line boundaries
  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.  
  125. You can use Perl's somewhat exotic C<..> operator (documented in
  126. L<perlop>):
  127.  
  128.     perl -ne 'print if /START/ .. /END/' file1 file2 ...
  129.  
  130. If you wanted text and not lines, you would use
  131.  
  132.     perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...
  133.  
  134. But if you want nested occurrences of C<START> through C<END>, you'll
  135. run up against the problem described in the question in this section
  136. on matching balanced text.
  137.  
  138. Here'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 $.
  146.     } 
  147.  
  148. =head2 I put a regular expression into $/ but it didn't work. What's wrong?
  149.  
  150. $/ must be a string, not a regular expression.  Awk has to be better
  151. for something. :-)
  152.  
  153. Actually, you could do this if you don't mind reading the whole file
  154. into memory:
  155.  
  156.     undef $/;
  157.     @records = split /your_pattern/, <FH>;
  158.  
  159. The Net::Telnet module (available from CPAN) has the capability to
  160. wait for a pattern in the input stream, or timeout if it doesn't
  161. appear within a certain time.
  162.  
  163.     ## Create a file with three lines.
  164.     open FH, ">file";
  165.     print FH "The first line\nThe second line\nThe third line\n";
  166.     close FH;
  167.  
  168.     ## Get a read/write filehandle to it.
  169.     $fh = new FileHandle "+<file";
  170.  
  171.     ## Attach it to a "stream" object.
  172.     use Net::Telnet;
  173.     $file = new Net::Telnet (-fhopen => $fh);
  174.  
  175.     ## Search for the second line and print out the third.
  176.     $file->waitfor('/second line\n/');
  177.     print $file->getline;
  178.  
  179. =head2 How do I substitute case insensitively on the LHS while preserving case on the RHS?
  180.  
  181. Here's a lovely Perlish solution by Larry Rosler.  It exploits
  182. properties of bitwise xor on ASCII strings.
  183.  
  184.     $_= "this is a TEsT case";
  185.  
  186.     $old = 'test';
  187.     $new = 'success';
  188.  
  189.     s{(\Q$old\E)}
  190.      { uc $new | (uc $1 ^ $1) .
  191.     (uc(substr $1, -1) ^ substr $1, -1) x
  192.         (length($new) - length $1)
  193.      }egi;
  194.  
  195.     print;
  196.  
  197. And here it is as a subroutine, modelled after the above:
  198.  
  199.     sub preserve_case($$) {
  200.     my ($old, $new) = @_;
  201.     my $mask = uc $old ^ $old;
  202.  
  203.     uc $new | $mask .
  204.         substr($mask, -1) x (length($new) - length($old))        
  205.     }
  206.  
  207.     $a = "this is a TEsT case";
  208.     $a =~ s/(test)/preserve_case($1, "success")/egi;
  209.     print "$a\n";
  210.  
  211. This prints:
  212.  
  213.     this is a SUcCESS case
  214.  
  215. Just to show that C programmers can write C in any programming language,
  216. if you prefer a more C-like solution, the following script makes the
  217. substitution have the same case, letter by letter, as the original.
  218. (It also happens to run about 240% slower than the Perlish solution runs.)
  219. If the substitution has more characters than the string being substituted,
  220. the case of the last character is used for the rest of the substitution.
  221.  
  222.     # Original by Nathan Torkington, massaged by Jeffrey Friedl
  223.     #
  224.     sub preserve_case($$)
  225.     {
  226.         my ($old, $new) = @_;
  227.         my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
  228.         my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
  229.         my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
  230.  
  231.         for ($i = 0; $i < $len; $i++) {
  232.             if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) {
  233.                 $state = 0;
  234.             } elsif (lc $c eq $c) {
  235.                 substr($new, $i, 1) = lc(substr($new, $i, 1));
  236.                 $state = 1;
  237.             } else {
  238.                 substr($new, $i, 1) = uc(substr($new, $i, 1));
  239.                 $state = 2;
  240.             }
  241.         }
  242.         # finish up with any remaining new (for when new is longer than old)
  243.         if ($newlen > $oldlen) {
  244.             if ($state == 1) {
  245.                 substr($new, $oldlen) = lc(substr($new, $oldlen));
  246.             } elsif ($state == 2) {
  247.                 substr($new, $oldlen) = uc(substr($new, $oldlen));
  248.             }
  249.         }
  250.         return $new;
  251.     }
  252.  
  253. =head2 How can I make C<\w> match national character sets?
  254.  
  255. See L<perllocale>.
  256.  
  257. =head2 How can I match a locale-smart version of C</[a-zA-Z]/>?
  258.  
  259. One alphabetic character would be C</[^\W\d_]/>, no matter what locale
  260. you're in.  Non-alphabetics would be C</[\W\d_]/> (assuming you don't
  261. consider an underscore a letter).
  262.  
  263. =head2 How can I quote a variable to use in a regex?
  264.  
  265. The Perl parser will expand $variable and @variable references in
  266. regular expressions unless the delimiter is a single quote.  Remember,
  267. too, that the right-hand side of a C<s///> substitution is considered
  268. a double-quoted string (see L<perlop> for more details).  Remember
  269. also that any regex special characters will be acted on unless you
  270. precede the substitution with \Q.  Here's an example:
  271.  
  272.     $string = "to die?";
  273.     $lhs = "die?";
  274.     $rhs = "sleep, no more";
  275.  
  276.     $string =~ s/\Q$lhs/$rhs/;
  277.     # $string is now "to sleep no more"
  278.  
  279. Without the \Q, the regex would also spuriously match "di".
  280.  
  281. =head2 What is C</o> really for?
  282.  
  283. Using a variable in a regular expression match forces a re-evaluation
  284. (and perhaps recompilation) each time the regular expression is
  285. encountered.  The C</o> modifier locks in the regex the first time
  286. it's used.  This always happens in a constant regular expression, and
  287. in fact, the pattern was compiled into the internal format at the same
  288. time your entire program was.
  289.  
  290. Use of C</o> is irrelevant unless variable interpolation is used in
  291. the pattern, and if so, the regex engine will neither know nor care
  292. whether the variables change after the pattern is evaluated the I<very
  293. first> time.
  294.  
  295. C</o> is often used to gain an extra measure of efficiency by not
  296. performing subsequent evaluations when you know it won't matter
  297. (because you know the variables won't change), or more rarely, when
  298. you don't want the regex to notice if they do.
  299.  
  300. For example, here's a "paragrep" program:
  301.  
  302.     $/ = '';  # paragraph mode
  303.     $pat = shift;
  304.     while (<>) {
  305.         print if /$pat/o;
  306.     }
  307.  
  308. =head2 How do I use a regular expression to strip C style comments from a file?
  309.  
  310. While this actually can be done, it's much harder than you'd think.
  311. For example, this one-liner
  312.  
  313.     perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c
  314.  
  315. will work in many but not all cases.  You see, it's too simple-minded for
  316. certain kinds of C programs, in particular, those with what appear to be
  317. comments in quoted strings.  For that, you'd need something like this,
  318. created by Jeffrey Friedl and later modified by Fred Curtis.
  319.  
  320.     $/ = undef;
  321.     $_ = <>;
  322.     s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs
  323.     print;
  324.  
  325. This could, of course, be more legibly written with the C</x> modifier, adding
  326. whitespace and comments.  Here it is expanded, courtesy of Fred Curtis.
  327.  
  328.     s{
  329.        /\*         ##  Start of /* ... */ comment
  330.        [^*]*\*+    ##  Non-* followed by 1-or-more *'s
  331.        (
  332.          [^/*][^*]*\*+
  333.        )*          ##  0-or-more things which don't start with /
  334.                    ##    but do end with '*'
  335.        /           ##  End of /* ... */ comment
  336.  
  337.      |         ##     OR  various things which aren't comments:
  338.  
  339.        (
  340.          "           ##  Start of " ... " string
  341.          (
  342.            \\.           ##  Escaped char
  343.          |               ##    OR
  344.            [^"\\]        ##  Non "\
  345.          )*
  346.          "           ##  End of " ... " string
  347.  
  348.        |         ##     OR
  349.  
  350.          '           ##  Start of ' ... ' string
  351.          (
  352.            \\.           ##  Escaped char
  353.          |               ##    OR
  354.            [^'\\]        ##  Non '\
  355.          )*
  356.          '           ##  End of ' ... ' string
  357.  
  358.        |         ##     OR
  359.  
  360.          .           ##  Anything other char
  361.          [^/"'\\]*   ##  Chars which doesn't start a comment, string or escape
  362.        )
  363.      }{$2}gxs;
  364.  
  365. A slight modification also removes C++ comments:
  366.  
  367.     s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//[^\n]*|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#$2#gs;
  368.  
  369. =head2 Can I use Perl regular expressions to match balanced text?
  370.  
  371. Although Perl regular expressions are more powerful than "mathematical"
  372. regular expressions because they feature conveniences like backreferences
  373. (C<\1> and its ilk), they still aren't powerful enough--with
  374. the possible exception of bizarre and experimental features in the
  375. development-track releases of Perl.  You still need to use non-regex
  376. techniques to parse balanced text, such as the text enclosed between
  377. matching parentheses or braces, for example.
  378.  
  379. An elaborate subroutine (for 7-bit ASCII only) to pull out balanced
  380. and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>,
  381. or C<(> and C<)> can be found in
  382. http://www.perl.com/CPAN/authors/id/TOMC/scripts/pull_quotes.gz .
  383.  
  384. The C::Scan module from CPAN contains such subs for internal use,
  385. but they are undocumented.
  386.  
  387. =head2 What does it mean that regexes are greedy?  How can I get around it?
  388.  
  389. Most people mean that greedy regexes match as much as they can.
  390. Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>,
  391. C<{}>) that are greedy rather than the whole pattern; Perl prefers local
  392. greed and immediate gratification to overall greed.  To get non-greedy
  393. versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>).
  394.  
  395. An example:
  396.  
  397.         $s1 = $s2 = "I am very very cold";
  398.         $s1 =~ s/ve.*y //;      # I am cold
  399.         $s2 =~ s/ve.*?y //;     # I am very cold
  400.  
  401. Notice how the second substitution stopped matching as soon as it
  402. encountered "y ".  The C<*?> quantifier effectively tells the regular
  403. expression engine to find a match as quickly as possible and pass
  404. control on to whatever is next in line, like you would if you were
  405. playing hot potato.
  406.  
  407. =head2 How do I process each word on each line?
  408.  
  409. Use the split function:
  410.  
  411.     while (<>) {
  412.     foreach $word ( split ) { 
  413.         # do something with $word here
  414.     } 
  415.     }
  416.  
  417. Note that this isn't really a word in the English sense; it's just
  418. chunks of consecutive non-whitespace characters.
  419.  
  420. To work with only alphanumeric sequences (including underscores), you
  421. might consider
  422.  
  423.     while (<>) {
  424.     foreach $word (m/(\w+)/g) {
  425.         # do something with $word here
  426.     }
  427.     }
  428.  
  429. =head2 How can I print out a word-frequency or line-frequency summary?
  430.  
  431. To do this, you have to parse out each word in the input stream.  We'll
  432. pretend that by word you mean chunk of alphabetics, hyphens, or
  433. apostrophes, rather than the non-whitespace chunk idea of a word given
  434. in the previous question:
  435.  
  436.     while (<>) {
  437.     while ( /(\b[^\W_\d][\w'-]+\b)/g ) {   # misses "`sheep'"
  438.         $seen{$1}++;
  439.     }
  440.     }
  441.     while ( ($word, $count) = each %seen ) {
  442.     print "$count $word\n";
  443.     }
  444.  
  445. If you wanted to do the same thing for lines, you wouldn't need a
  446. regular expression:
  447.  
  448.     while (<>) { 
  449.     $seen{$_}++;
  450.     }
  451.     while ( ($line, $count) = each %seen ) {
  452.     print "$count $line";
  453.     }
  454.  
  455. If you want these output in a sorted order, see L<perlfaq4>: ``How do I
  456. sort a hash (optionally by value instead of key)?''.
  457.  
  458. =head2 How can I do approximate matching?
  459.  
  460. See the module String::Approx available from CPAN.
  461.  
  462. =head2 How do I efficiently match many regular expressions at once?
  463.  
  464. The following is extremely inefficient:
  465.  
  466.     # slow but obvious way
  467.     @popstates = qw(CO ON MI WI MN);
  468.     while (defined($line = <>)) {
  469.     for $state (@popstates) {
  470.         if ($line =~ /\b$state\b/i) {  
  471.         print $line;
  472.         last;
  473.         }
  474.     }
  475.     }                                        
  476.  
  477. That's because Perl has to recompile all those patterns for each of
  478. the lines of the file.  As of the 5.005 release, there's a much better
  479. approach, one which makes use of the new C<qr//> operator:
  480.  
  481.     # use spiffy new qr// operator, with /i flag even
  482.     use 5.005;
  483.     @popstates = qw(CO ON MI WI MN);
  484.     @poppats   = map { qr/\b$_\b/i } @popstates;
  485.     while (defined($line = <>)) {
  486.     for $patobj (@poppats) {
  487.         print $line if $line =~ /$patobj/;
  488.     }
  489.     }
  490.  
  491. =head2 Why don't word-boundary searches with C<\b> work for me?
  492.  
  493. Two common misconceptions are that C<\b> is a synonym for C<\s+> and
  494. that it's the edge between whitespace characters and non-whitespace
  495. characters.  Neither is correct.  C<\b> is the place between a C<\w>
  496. character and a C<\W> character (that is, C<\b> is the edge of a
  497. "word").  It's a zero-width assertion, just like C<^>, C<$>, and all
  498. the other anchors, so it doesn't consume any characters.  L<perlre>
  499. describes the behavior of all the regex metacharacters.
  500.  
  501. Here are examples of the incorrect application of C<\b>, with fixes:
  502.  
  503.     "two words" =~ /(\w+)\b(\w+)/;        # WRONG
  504.     "two words" =~ /(\w+)\s+(\w+)/;        # right
  505.  
  506.     " =matchless= text" =~ /\b=(\w+)=\b/;   # WRONG
  507.     " =matchless= text" =~ /=(\w+)=/;       # right
  508.  
  509. Although they may not do what you thought they did, C<\b> and C<\B>
  510. can still be quite useful.  For an example of the correct use of
  511. C<\b>, see the example of matching duplicate words over multiple
  512. lines.
  513.  
  514. An example of using C<\B> is the pattern C<\Bis\B>.  This will find
  515. occurrences of "is" on the insides of words only, as in "thistle", but
  516. not "this" or "island".
  517.  
  518. =head2 Why does using $&, $`, or $' slow my program down?
  519.  
  520. Once Perl sees that you need one of these variables anywhere in
  521. the program, it provides them on each and every pattern match.
  522. The same mechanism that handles these provides for the use of $1, $2,
  523. etc., so you pay the same price for each regex that contains capturing
  524. parentheses.  If you never use $&, etc., in your script, then regexes
  525. I<without> capturing parentheses won't be penalized. So avoid $&, $',
  526. and $` if you can, but if you can't, once you've used them at all, use
  527. them at will because you've already paid the price.  Remember that some
  528. algorithms really appreciate them.  As of the 5.005 release.  the $&
  529. variable is no longer "expensive" the way the other two are.
  530.  
  531. =head2 What good is C<\G> in a regular expression?
  532.  
  533. The notation C<\G> is used in a match or substitution in conjunction with
  534. the C</g> modifier to anchor the regular expression to the point just past
  535. where the last match occurred, i.e. the pos() point.  A failed match resets
  536. the position of C<\G> unless the C</c> modifier is in effect. C<\G> can be
  537. used in a match without the C</g> modifier; it acts the same (i.e. still
  538. anchors at the pos() point) but of course only matches once and does not
  539. update pos(), as non-C</g> expressions never do. C<\G> in an expression
  540. applied to a target string that has never been matched against a C</g>
  541. expression before or has had its pos() reset is functionally equivalent to
  542. C<\A>, which matches at the beginning of the string.
  543.  
  544. For example, suppose you had a line of text quoted in standard mail
  545. and Usenet notation, (that is, with leading C<< > >> characters), and
  546. you want change each leading C<< > >> into a corresponding C<:>.  You
  547. could do so in this way:
  548.  
  549.      s/^(>+)/':' x length($1)/gem;
  550.  
  551. Or, using C<\G>, the much simpler (and faster):
  552.  
  553.     s/\G>/:/g;
  554.  
  555. A more sophisticated use might involve a tokenizer.  The following
  556. lex-like example is courtesy of Jeffrey Friedl.  It did not work in
  557. 5.003 due to bugs in that release, but does work in 5.004 or better.
  558. (Note the use of C</c>, which prevents a failed match with C</g> from
  559. resetting the search position back to the beginning of the string.)
  560.  
  561.     while (<>) {
  562.       chomp;
  563.       PARSER: {
  564.            m/ \G( \d+\b    )/gcx    && do { print "number: $1\n";  redo; };
  565.            m/ \G( \w+      )/gcx    && do { print "word:   $1\n";  redo; };
  566.            m/ \G( \s+      )/gcx    && do { print "space:  $1\n";  redo; };
  567.            m/ \G( [^\w\d]+ )/gcx    && do { print "other:  $1\n";  redo; };
  568.       }
  569.     }
  570.  
  571. Of course, that could have been written as
  572.  
  573.     while (<>) {
  574.       chomp;
  575.       PARSER: {
  576.        if ( /\G( \d+\b    )/gcx  {
  577.         print "number: $1\n";
  578.         redo PARSER;
  579.        }
  580.        if ( /\G( \w+      )/gcx  {
  581.         print "word: $1\n";
  582.         redo PARSER;
  583.        }
  584.        if ( /\G( \s+      )/gcx  {
  585.         print "space: $1\n";
  586.         redo PARSER;
  587.        }
  588.        if ( /\G( [^\w\d]+ )/gcx  {
  589.         print "other: $1\n";
  590.         redo PARSER;
  591.        }
  592.       }
  593.     }
  594.  
  595. but then you lose the vertical alignment of the regular expressions.
  596.  
  597. =head2 Are Perl regexes DFAs or NFAs?  Are they POSIX compliant?
  598.  
  599. While it's true that Perl's regular expressions resemble the DFAs
  600. (deterministic finite automata) of the egrep(1) program, they are in
  601. fact implemented as NFAs (non-deterministic finite automata) to allow
  602. backtracking and backreferencing.  And they aren't POSIX-style either,
  603. because those guarantee worst-case behavior for all cases.  (It seems
  604. that some people prefer guarantees of consistency, even when what's
  605. guaranteed is slowness.)  See the book "Mastering Regular Expressions"
  606. (from O'Reilly) by Jeffrey Friedl for all the details you could ever
  607. hope to know on these matters (a full citation appears in
  608. L<perlfaq2>).
  609.  
  610. =head2 What's wrong with using grep or map in a void context?
  611.  
  612. Both grep and map build a return list, regardless of their context.
  613. This means you're making Perl go to the trouble of building up a
  614. return list that you then just ignore.  That's no way to treat a
  615. programming language, you insensitive scoundrel!
  616.  
  617. =head2 How can I match strings with multibyte characters?
  618.  
  619. This is hard, and there's no good way.  Perl does not directly support
  620. wide characters.  It pretends that a byte and a character are
  621. synonymous.  The following set of approaches was offered by Jeffrey
  622. Friedl, whose article in issue #5 of The Perl Journal talks about this
  623. very matter.
  624.  
  625. Let's suppose you have some weird Martian encoding where pairs of
  626. ASCII uppercase letters encode single Martian letters (i.e. the two
  627. bytes "CV" make a single Martian letter, as do the two bytes "SG",
  628. "VS", "XX", etc.). Other bytes represent single characters, just like
  629. ASCII.
  630.  
  631. So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
  632. nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.
  633.  
  634. Now, say you want to search for the single character C</GX/>. Perl
  635. doesn't know about Martian, so it'll find the two bytes "GX" in the "I
  636. am CVSGXX!"  string, even though that character isn't there: it just
  637. looks like it is because "SG" is next to "XX", but there's no real
  638. "GX".  This is a big problem.
  639.  
  640. Here are a few ways, all painful, to deal with it:
  641.  
  642.    $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian'' bytes
  643.                                       # are no longer adjacent.
  644.    print "found GX!\n" if $martian =~ /GX/;
  645.  
  646. Or like this:
  647.  
  648.    @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
  649.    # above is conceptually similar to:     @chars = $text =~ m/(.)/g;
  650.    #
  651.    foreach $char (@chars) {
  652.        print "found GX!\n", last if $char eq 'GX';
  653.    }
  654.  
  655. Or like this:
  656.  
  657.    while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) {  # \G probably unneeded
  658.        print "found GX!\n", last if $1 eq 'GX';
  659.    }
  660.  
  661. Or like this:
  662.  
  663.     die "sorry, Perl doesn't (yet) have Martian support )-:\n";
  664.  
  665. There are many double- (and multi-) byte encodings commonly used these
  666. days.  Some versions of these have 1-, 2-, 3-, and 4-byte characters,
  667. all mixed.
  668.  
  669. =head2 How do I match a pattern that is supplied by the user?
  670.  
  671. Well, if it's really a pattern, then just use
  672.  
  673.     chomp($pattern = <STDIN>);
  674.     if ($line =~ /$pattern/) { }
  675.  
  676. Alternatively, since you have no guarantee that your user entered
  677. a valid regular expression, trap the exception this way:
  678.  
  679.     if (eval { $line =~ /$pattern/ }) { }
  680.  
  681. If all you really want to search for a string, not a pattern,
  682. then you should either use the index() function, which is made for
  683. string searching, or if you can't be disabused of using a pattern
  684. match on a non-pattern, then be sure to use C<\Q>...C<\E>, documented
  685. in L<perlre>.
  686.  
  687.     $pattern = <STDIN>;
  688.  
  689.     open (FILE, $input) or die "Couldn't open input $input: $!; aborting";
  690.     while (<FILE>) {
  691.     print if /\Q$pattern\E/;
  692.     }
  693.     close FILE;
  694.  
  695. =head1 AUTHOR AND COPYRIGHT
  696.  
  697. Copyright (c) 1997-1999 Tom Christiansen and Nathan Torkington.
  698. All rights reserved.
  699.  
  700. When included as part of the Standard Version of Perl, or as part of
  701. its complete documentation whether printed or otherwise, this work
  702. may be distributed only under the terms of Perl's Artistic License.
  703. Any distribution of this file or derivatives thereof I<outside>
  704. of that package require that special arrangements be made with
  705. copyright holder.
  706.  
  707. Irrespective of its distribution, all code examples in this file
  708. are hereby placed into the public domain.  You are permitted and
  709. encouraged to use this code in your own programs for fun
  710. or for profit as you see fit.  A simple comment in the code giving
  711. credit would be courteous but is not required.
  712.