Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

711 lines
25 KiB

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