Commit | Line | Data |
---|---|---|
68dc0745 | 1 | =head1 NAME |
2 | ||
92c2ed05 | 3 | perlfaq6 - Regexps ($Revision: 1.22 $, $Date: 1998/07/16 14:01:07 $) |
68dc0745 | 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 the section on Data and the Networking one on | |
12 | networking, to be precise). | |
13 | ||
54310121 | 14 | =head2 How can I hope to use regular expressions without creating illegible and unmaintainable code? |
68dc0745 | 15 | |
16 | Three techniques can make regular expressions maintainable and | |
17 | understandable. | |
18 | ||
19 | =over 4 | |
20 | ||
21 | =item Comments Outside the Regexp | |
22 | ||
23 | Describe what you're doing and how you're doing it, using normal Perl | |
24 | comments. | |
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 | |
30 | =item Comments Inside the Regexp | |
31 | ||
32 | The C</x> modifier causes whitespace to be ignored in a regexp pattern | |
33 | (except in a character class), and also allows you to use normal | |
34 | comments there, too. As you can imagine, whitespace and comments help | |
35 | a lot. | |
36 | ||
37 | C</x> lets you turn this: | |
38 | ||
39 | s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs; | |
40 | ||
41 | into 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 | ||
54 | It's still not quite so clear as prose, but it is very useful for | |
55 | describing the meaning of each part of the pattern. | |
56 | ||
57 | =item Different Delimiters | |
58 | ||
59 | While we normally think of patterns as being delimited with C</> | |
60 | characters, they can be delimited by almost any character. L<perlre> | |
61 | describes this. For example, the C<s///> above uses braces as | |
62 | delimiters. Selecting another delimiter can avoid quoting the | |
63 | delimiter 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 TC |
72 | Either 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 | |
74 | pattern (possibly). | |
68dc0745 | 75 | |
76 | There are many ways to get multiline data into a string. If you want | |
77 | it to happen automatically while reading input, you'll want to set $/ | |
78 | (probably to '' for paragraphs or C<undef> for the whole file) to | |
79 | allow you to read more than one line at a time. | |
80 | ||
81 | Read L<perlre> to help you decide which of C</s> and C</m> (or both) | |
82 | you might want to use: C</s> allows dot to include newline, and C</m> | |
83 | allows caret and dollar to match next to a newline, not just at the | |
84 | end of the string. You do need to make sure that you've actually | |
85 | got a multiline string in there. | |
86 | ||
87 | For example, this program detects duplicate words, even when they span | |
88 | line breaks (but not paragraph ones). For this example, we don't need | |
89 | C</s> because we aren't using dot in a regular expression that we want | |
90 | to cross line boundaries. Neither do we need C</m> because we aren't | |
91 | wanting caret or dollar to match at any point inside the record next | |
92 | to newlines. But it's imperative that $/ be set to something other | |
93 | than the default, or else we won't actually ever have a multiline | |
94 | record 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 | |
103 | Here's code that finds sentences that begin with "From " (which would | |
104 | be 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 | ||
113 | Here'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 | ||
124 | You can use Perl's somewhat exotic C<..> operator (documented in | |
125 | L<perlop>): | |
126 | ||
127 | perl -ne 'print if /START/ .. /END/' file1 file2 ... | |
128 | ||
129 | If you wanted text and not lines, you would use | |
130 | ||
131 | perl -0777 -pe 'print "$1\n" while /START(.*?)END/gs' file1 file2 ... | |
132 | ||
133 | But if you want nested occurrences of C<START> through C<END>, you'll | |
134 | run up against the problem described in the question in this section | |
135 | on matching balanced text. | |
136 | ||
5a964f20 TC |
137 | Here'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 | |
150 | for something. :-) | |
151 | ||
fc36a67e | 152 | Actually, you could do this if you don't mind reading the whole file |
153 | into memory: | |
68dc0745 | 154 | |
155 | undef $/; | |
156 | @records = split /your_pattern/, <FH>; | |
157 | ||
3fe9a6f1 | 158 | The Net::Telnet module (available from CPAN) has the capability to |
159 | wait for a pattern in the input stream, or timeout if it doesn't | |
160 | appear 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 | ||
180 | It depends on what you mean by "preserving case". The following | |
181 | script makes the substitution have the same case, letter by letter, as | |
182 | the original. If the substitution has more characters than the string | |
183 | being substituted, the case of the last character is used for the rest | |
184 | of the substitution. | |
185 | ||
186 | # Original by Nathan Torkington, massaged by Jeffrey Friedl | |
187 | # | |
188 | sub preserve_case($$) | |
189 | { | |
190 | my ($old, $new) = @_; | |
191 | my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc | |
192 | my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new)); | |
193 | my ($len) = $oldlen < $newlen ? $oldlen : $newlen; | |
194 | ||
195 | for ($i = 0; $i < $len; $i++) { | |
196 | if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) { | |
197 | $state = 0; | |
198 | } elsif (lc $c eq $c) { | |
199 | substr($new, $i, 1) = lc(substr($new, $i, 1)); | |
200 | $state = 1; | |
201 | } else { | |
202 | substr($new, $i, 1) = uc(substr($new, $i, 1)); | |
203 | $state = 2; | |
204 | } | |
205 | } | |
206 | # finish up with any remaining new (for when new is longer than old) | |
207 | if ($newlen > $oldlen) { | |
208 | if ($state == 1) { | |
209 | substr($new, $oldlen) = lc(substr($new, $oldlen)); | |
210 | } elsif ($state == 2) { | |
211 | substr($new, $oldlen) = uc(substr($new, $oldlen)); | |
212 | } | |
213 | } | |
214 | return $new; | |
215 | } | |
216 | ||
217 | $a = "this is a TEsT case"; | |
218 | $a =~ s/(test)/preserve_case($1, "success")/gie; | |
219 | print "$a\n"; | |
220 | ||
221 | This prints: | |
222 | ||
223 | this is a SUcCESS case | |
224 | ||
5a964f20 | 225 | =head2 How can I make C<\w> match national character sets? |
68dc0745 | 226 | |
227 | See L<perllocale>. | |
228 | ||
229 | =head2 How can I match a locale-smart version of C</[a-zA-Z]/>? | |
230 | ||
231 | One alphabetic character would be C</[^\W\d_]/>, no matter what locale | |
54310121 | 232 | you're in. Non-alphabetics would be C</[\W\d_]/> (assuming you don't |
68dc0745 | 233 | consider an underscore a letter). |
234 | ||
54310121 | 235 | =head2 How can I quote a variable to use in a regexp? |
68dc0745 | 236 | |
237 | The Perl parser will expand $variable and @variable references in | |
238 | regular expressions unless the delimiter is a single quote. Remember, | |
239 | too, that the right-hand side of a C<s///> substitution is considered | |
240 | a double-quoted string (see L<perlop> for more details). Remember | |
241 | also that any regexp special characters will be acted on unless you | |
242 | precede the substitution with \Q. Here's an example: | |
243 | ||
244 | $string = "to die?"; | |
245 | $lhs = "die?"; | |
246 | $rhs = "sleep no more"; | |
247 | ||
248 | $string =~ s/\Q$lhs/$rhs/; | |
249 | # $string is now "to sleep no more" | |
250 | ||
251 | Without the \Q, the regexp would also spuriously match "di". | |
252 | ||
253 | =head2 What is C</o> really for? | |
254 | ||
46fc3d4c | 255 | Using a variable in a regular expression match forces a re-evaluation |
68dc0745 | 256 | (and perhaps recompilation) each time through. The C</o> modifier |
257 | locks in the regexp the first time it's used. This always happens in a | |
258 | constant regular expression, and in fact, the pattern was compiled | |
259 | into the internal format at the same time your entire program was. | |
260 | ||
261 | Use of C</o> is irrelevant unless variable interpolation is used in | |
262 | the pattern, and if so, the regexp engine will neither know nor care | |
263 | whether the variables change after the pattern is evaluated the I<very | |
264 | first> time. | |
265 | ||
266 | C</o> is often used to gain an extra measure of efficiency by not | |
267 | performing subsequent evaluations when you know it won't matter | |
268 | (because you know the variables won't change), or more rarely, when | |
269 | you don't want the regexp to notice if they do. | |
270 | ||
271 | For example, here's a "paragrep" program: | |
272 | ||
273 | $/ = ''; # paragraph mode | |
274 | $pat = shift; | |
275 | while (<>) { | |
276 | print if /$pat/o; | |
277 | } | |
278 | ||
279 | =head2 How do I use a regular expression to strip C style comments from a file? | |
280 | ||
281 | While this actually can be done, it's much harder than you'd think. | |
282 | For example, this one-liner | |
283 | ||
284 | perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c | |
285 | ||
286 | will work in many but not all cases. You see, it's too simple-minded for | |
287 | certain kinds of C programs, in particular, those with what appear to be | |
288 | comments in quoted strings. For that, you'd need something like this, | |
289 | created by Jeffrey Friedl: | |
290 | ||
291 | $/ = undef; | |
292 | $_ = <>; | |
293 | s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g; | |
294 | print; | |
295 | ||
296 | This could, of course, be more legibly written with the C</x> modifier, adding | |
297 | whitespace and comments. | |
298 | ||
299 | =head2 Can I use Perl regular expressions to match balanced text? | |
300 | ||
301 | Although Perl regular expressions are more powerful than "mathematical" | |
302 | regular expressions, because they feature conveniences like backreferences | |
303 | (C<\1> and its ilk), they still aren't powerful enough. You still need | |
304 | to use non-regexp techniques to parse balanced text, such as the text | |
305 | enclosed between matching parentheses or braces, for example. | |
306 | ||
307 | An elaborate subroutine (for 7-bit ASCII only) to pull out balanced | |
308 | and possibly nested single chars, like C<`> and C<'>, C<{> and C<}>, | |
309 | or C<(> and C<)> can be found in | |
310 | http://www.perl.com/CPAN/authors/id/TOMC/scripts/pull_quotes.gz . | |
311 | ||
312 | The C::Scan module from CPAN contains such subs for internal usage, | |
313 | but they are undocumented. | |
314 | ||
315 | =head2 What does it mean that regexps are greedy? How can I get around it? | |
316 | ||
317 | Most people mean that greedy regexps match as much as they can. | |
318 | Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>, | |
319 | C<{}>) that are greedy rather than the whole pattern; Perl prefers local | |
320 | greed and immediate gratification to overall greed. To get non-greedy | |
321 | versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>). | |
322 | ||
323 | An example: | |
324 | ||
325 | $s1 = $s2 = "I am very very cold"; | |
326 | $s1 =~ s/ve.*y //; # I am cold | |
327 | $s2 =~ s/ve.*?y //; # I am very cold | |
328 | ||
329 | Notice how the second substitution stopped matching as soon as it | |
330 | encountered "y ". The C<*?> quantifier effectively tells the regular | |
331 | expression engine to find a match as quickly as possible and pass | |
332 | control on to whatever is next in line, like you would if you were | |
333 | playing hot potato. | |
334 | ||
335 | =head2 How do I process each word on each line? | |
336 | ||
337 | Use the split function: | |
338 | ||
339 | while (<>) { | |
fc36a67e | 340 | foreach $word ( split ) { |
68dc0745 | 341 | # do something with $word here |
fc36a67e | 342 | } |
54310121 | 343 | } |
68dc0745 | 344 | |
54310121 | 345 | Note that this isn't really a word in the English sense; it's just |
346 | chunks of consecutive non-whitespace characters. | |
68dc0745 | 347 | |
348 | To work with only alphanumeric sequences, you might consider | |
349 | ||
350 | while (<>) { | |
351 | foreach $word (m/(\w+)/g) { | |
352 | # do something with $word here | |
353 | } | |
354 | } | |
355 | ||
356 | =head2 How can I print out a word-frequency or line-frequency summary? | |
357 | ||
358 | To do this, you have to parse out each word in the input stream. We'll | |
54310121 | 359 | pretend that by word you mean chunk of alphabetics, hyphens, or |
360 | apostrophes, rather than the non-whitespace chunk idea of a word given | |
68dc0745 | 361 | in the previous question: |
362 | ||
363 | while (<>) { | |
364 | while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'" | |
365 | $seen{$1}++; | |
54310121 | 366 | } |
367 | } | |
68dc0745 | 368 | while ( ($word, $count) = each %seen ) { |
369 | print "$count $word\n"; | |
54310121 | 370 | } |
68dc0745 | 371 | |
372 | If you wanted to do the same thing for lines, you wouldn't need a | |
373 | regular expression: | |
374 | ||
fc36a67e | 375 | while (<>) { |
68dc0745 | 376 | $seen{$_}++; |
54310121 | 377 | } |
68dc0745 | 378 | while ( ($line, $count) = each %seen ) { |
379 | print "$count $line"; | |
380 | } | |
381 | ||
382 | If you want these output in a sorted order, see the section on Hashes. | |
383 | ||
384 | =head2 How can I do approximate matching? | |
385 | ||
386 | See the module String::Approx available from CPAN. | |
387 | ||
388 | =head2 How do I efficiently match many regular expressions at once? | |
389 | ||
390 | The following is super-inefficient: | |
391 | ||
392 | while (<FH>) { | |
393 | foreach $pat (@patterns) { | |
394 | if ( /$pat/ ) { | |
395 | # do something | |
396 | } | |
397 | } | |
398 | } | |
399 | ||
400 | Instead, you either need to use one of the experimental Regexp extension | |
401 | modules from CPAN (which might well be overkill for your purposes), | |
402 | or else put together something like this, inspired from a routine | |
403 | in Jeffrey Friedl's book: | |
404 | ||
405 | sub _bm_build { | |
406 | my $condition = shift; | |
407 | my @regexp = @_; # this MUST not be local(); need my() | |
408 | my $expr = join $condition => map { "m/\$regexp[$_]/o" } (0..$#regexp); | |
409 | my $match_func = eval "sub { $expr }"; | |
410 | die if $@; # propagate $@; this shouldn't happen! | |
411 | return $match_func; | |
412 | } | |
413 | ||
414 | sub bm_and { _bm_build('&&', @_) } | |
415 | sub bm_or { _bm_build('||', @_) } | |
416 | ||
417 | $f1 = bm_and qw{ | |
418 | xterm | |
419 | (?i)window | |
420 | }; | |
421 | ||
422 | $f2 = bm_or qw{ | |
423 | \b[Ff]ree\b | |
424 | \bBSD\B | |
425 | (?i)sys(tem)?\s*[V5]\b | |
426 | }; | |
427 | ||
428 | # feed me /etc/termcap, prolly | |
429 | while ( <> ) { | |
430 | print "1: $_" if &$f1; | |
431 | print "2: $_" if &$f2; | |
432 | } | |
433 | ||
434 | =head2 Why don't word-boundary searches with C<\b> work for me? | |
435 | ||
436 | Two common misconceptions are that C<\b> is a synonym for C<\s+>, and | |
437 | that it's the edge between whitespace characters and non-whitespace | |
438 | characters. Neither is correct. C<\b> is the place between a C<\w> | |
439 | character and a C<\W> character (that is, C<\b> is the edge of a | |
440 | "word"). It's a zero-width assertion, just like C<^>, C<$>, and all | |
441 | the other anchors, so it doesn't consume any characters. L<perlre> | |
442 | describes the behaviour of all the regexp metacharacters. | |
443 | ||
444 | Here are examples of the incorrect application of C<\b>, with fixes: | |
445 | ||
446 | "two words" =~ /(\w+)\b(\w+)/; # WRONG | |
447 | "two words" =~ /(\w+)\s+(\w+)/; # right | |
448 | ||
449 | " =matchless= text" =~ /\b=(\w+)=\b/; # WRONG | |
450 | " =matchless= text" =~ /=(\w+)=/; # right | |
451 | ||
452 | Although they may not do what you thought they did, C<\b> and C<\B> | |
453 | can still be quite useful. For an example of the correct use of | |
454 | C<\b>, see the example of matching duplicate words over multiple | |
455 | lines. | |
456 | ||
457 | An example of using C<\B> is the pattern C<\Bis\B>. This will find | |
458 | occurrences of "is" on the insides of words only, as in "thistle", but | |
459 | not "this" or "island". | |
460 | ||
461 | =head2 Why does using $&, $`, or $' slow my program down? | |
462 | ||
463 | Because once Perl sees that you need one of these variables anywhere | |
464 | in the program, it has to provide them on each and every pattern | |
465 | match. The same mechanism that handles these provides for the use of | |
466 | $1, $2, etc., so you pay the same price for each regexp that contains | |
467 | capturing parentheses. But if you never use $&, etc., in your script, | |
468 | then regexps I<without> capturing parentheses won't be penalized. So | |
469 | avoid $&, $', and $` if you can, but if you can't (and some algorithms | |
470 | really appreciate them), once you've used them once, use them at will, | |
471 | because you've already paid the price. | |
472 | ||
473 | =head2 What good is C<\G> in a regular expression? | |
474 | ||
475 | The notation C<\G> is used in a match or substitution in conjunction the | |
476 | C</g> modifier (and ignored if there's no C</g>) to anchor the regular | |
477 | expression to the point just past where the last match occurred, i.e. the | |
478 | pos() point. | |
479 | ||
480 | For example, suppose you had a line of text quoted in standard mail | |
481 | and Usenet notation, (that is, with leading C<E<gt>> characters), and | |
482 | you want change each leading C<E<gt>> into a corresponding C<:>. You | |
483 | could do so in this way: | |
484 | ||
485 | s/^(>+)/':' x length($1)/gem; | |
486 | ||
487 | Or, using C<\G>, the much simpler (and faster): | |
488 | ||
489 | s/\G>/:/g; | |
490 | ||
491 | A more sophisticated use might involve a tokenizer. The following | |
492 | lex-like example is courtesy of Jeffrey Friedl. It did not work in | |
c90c0ff4 | 493 | 5.003 due to bugs in that release, but does work in 5.004 or better. |
494 | (Note the use of C</c>, which prevents a failed match with C</g> from | |
495 | resetting the search position back to the beginning of the string.) | |
68dc0745 | 496 | |
497 | while (<>) { | |
498 | chomp; | |
499 | PARSER: { | |
c90c0ff4 | 500 | m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; }; |
501 | m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; }; | |
502 | m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; }; | |
503 | m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; }; | |
68dc0745 | 504 | } |
505 | } | |
506 | ||
507 | Of course, that could have been written as | |
508 | ||
509 | while (<>) { | |
510 | chomp; | |
511 | PARSER: { | |
c90c0ff4 | 512 | if ( /\G( \d+\b )/gcx { |
68dc0745 | 513 | print "number: $1\n"; |
514 | redo PARSER; | |
515 | } | |
c90c0ff4 | 516 | if ( /\G( \w+ )/gcx { |
68dc0745 | 517 | print "word: $1\n"; |
518 | redo PARSER; | |
519 | } | |
c90c0ff4 | 520 | if ( /\G( \s+ )/gcx { |
68dc0745 | 521 | print "space: $1\n"; |
522 | redo PARSER; | |
523 | } | |
c90c0ff4 | 524 | if ( /\G( [^\w\d]+ )/gcx { |
68dc0745 | 525 | print "other: $1\n"; |
526 | redo PARSER; | |
527 | } | |
528 | } | |
529 | } | |
530 | ||
531 | But then you lose the vertical alignment of the regular expressions. | |
532 | ||
533 | =head2 Are Perl regexps DFAs or NFAs? Are they POSIX compliant? | |
534 | ||
535 | While it's true that Perl's regular expressions resemble the DFAs | |
536 | (deterministic finite automata) of the egrep(1) program, they are in | |
46fc3d4c | 537 | fact implemented as NFAs (non-deterministic finite automata) to allow |
68dc0745 | 538 | backtracking and backreferencing. And they aren't POSIX-style either, |
539 | because those guarantee worst-case behavior for all cases. (It seems | |
540 | that some people prefer guarantees of consistency, even when what's | |
541 | guaranteed is slowness.) See the book "Mastering Regular Expressions" | |
542 | (from O'Reilly) by Jeffrey Friedl for all the details you could ever | |
543 | hope to know on these matters (a full citation appears in | |
544 | L<perlfaq2>). | |
545 | ||
546 | =head2 What's wrong with using grep or map in a void context? | |
547 | ||
92c2ed05 GS |
548 | Both grep and map build a return list, regardless of their context. |
549 | This means you're making Perl go to the trouble of building up a | |
550 | return list that you then just ignore. That's no way to treat a | |
551 | programming language, you insensitive scoundrel! | |
68dc0745 | 552 | |
54310121 | 553 | =head2 How can I match strings with multibyte characters? |
68dc0745 | 554 | |
555 | This is hard, and there's no good way. Perl does not directly support | |
556 | wide characters. It pretends that a byte and a character are | |
557 | synonymous. The following set of approaches was offered by Jeffrey | |
558 | Friedl, whose article in issue #5 of The Perl Journal talks about this | |
559 | very matter. | |
560 | ||
fc36a67e | 561 | Let's suppose you have some weird Martian encoding where pairs of |
562 | ASCII uppercase letters encode single Martian letters (i.e. the two | |
563 | bytes "CV" make a single Martian letter, as do the two bytes "SG", | |
564 | "VS", "XX", etc.). Other bytes represent single characters, just like | |
565 | ASCII. | |
68dc0745 | 566 | |
fc36a67e | 567 | So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the |
568 | nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'. | |
68dc0745 | 569 | |
570 | Now, say you want to search for the single character C</GX/>. Perl | |
fc36a67e | 571 | doesn't know about Martian, so it'll find the two bytes "GX" in the "I |
572 | am CVSGXX!" string, even though that character isn't there: it just | |
573 | looks like it is because "SG" is next to "XX", but there's no real | |
574 | "GX". This is a big problem. | |
68dc0745 | 575 | |
576 | Here are a few ways, all painful, to deal with it: | |
577 | ||
3fe9a6f1 | 578 | $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian'' bytes |
68dc0745 | 579 | # are no longer adjacent. |
580 | print "found GX!\n" if $martian =~ /GX/; | |
581 | ||
582 | Or like this: | |
583 | ||
584 | @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g; | |
585 | # above is conceptually similar to: @chars = $text =~ m/(.)/g; | |
586 | # | |
587 | foreach $char (@chars) { | |
588 | print "found GX!\n", last if $char eq 'GX'; | |
589 | } | |
590 | ||
591 | Or like this: | |
592 | ||
593 | while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded | |
54310121 | 594 | print "found GX!\n", last if $1 eq 'GX'; |
68dc0745 | 595 | } |
596 | ||
597 | Or like this: | |
598 | ||
599 | die "sorry, Perl doesn't (yet) have Martian support )-:\n"; | |
600 | ||
601 | In addition, a sample program which converts half-width to full-width | |
54310121 | 602 | katakana (in Shift-JIS or EUC encoding) is available from CPAN as |
68dc0745 | 603 | |
604 | =for Tom make it so | |
605 | ||
46fc3d4c | 606 | There are many double- (and multi-) byte encodings commonly used these |
68dc0745 | 607 | days. Some versions of these have 1-, 2-, 3-, and 4-byte characters, |
608 | all mixed. | |
609 | ||
610 | =head1 AUTHOR AND COPYRIGHT | |
611 | ||
5a964f20 TC |
612 | Copyright (c) 1997, 1998 Tom Christiansen and Nathan Torkington. |
613 | All rights reserved. | |
614 | ||
615 | When included as part of the Standard Version of Perl, or as part of | |
616 | its complete documentation whether printed or otherwise, this work | |
617 | may be distributed only under the terms of Perl's Artistic License. | |
618 | Any distribution of this file or derivatives thereof I<outside> | |
619 | of that package require that special arrangements be made with | |
620 | copyright holder. | |
621 | ||
622 | Irrespective of its distribution, all code examples in this file | |
623 | are hereby placed into the public domain. You are permitted and | |
624 | encouraged to use this code in your own programs for fun | |
625 | or for profit as you see fit. A simple comment in the code giving | |
626 | credit would be courteous but is not required. |