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