Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man1 / perlfaq6.1
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "PERLFAQ6 1"
132.TH PERLFAQ6 1 "2002-06-08" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134perlfaq6 \- Regular Expressions ($Revision: 1.12 $, $Date: 2002/06/01 22:31:09 $)
135.SH "DESCRIPTION"
136.IX Header "DESCRIPTION"
137This section is surprisingly small because the rest of the \s-1FAQ\s0 is
138littered with answers involving regular expressions. For example,
139decoding a \s-1URL\s0 and checking whether something is a number are handled
140with regular expressions, but those answers are found elsewhere in
141this document (in perlfaq9: ``How do I decode or create those %\-encodings
142on the web'' and perlfaq4: ``How do I determine whether a scalar is
143a number/whole/integer/float'', to be precise).
144.Sh "How can I hope to use regular expressions without creating illegible and unmaintainable code?"
145.IX Subsection "How can I hope to use regular expressions without creating illegible and unmaintainable code?"
146Three techniques can make regular expressions maintainable and
147understandable.
148.IP "Comments Outside the Regex" 4
149.IX Item "Comments Outside the Regex"
150Describe what you're doing and how you're doing it, using normal Perl
151comments.
152.Sp
153.Vb 3
154\& # turn the line into the first word, a colon, and the
155\& # number of characters on the rest of the line
156\& s/^(\ew+)(.*)/ lc($1) . ":" . length($2) /meg;
157.Ve
158.IP "Comments Inside the Regex" 4
159.IX Item "Comments Inside the Regex"
160The \f(CW\*(C`/x\*(C'\fR modifier causes whitespace to be ignored in a regex pattern
161(except in a character class), and also allows you to use normal
162comments there, too. As you can imagine, whitespace and comments help
163a lot.
164.Sp
165\&\f(CW\*(C`/x\*(C'\fR lets you turn this:
166.Sp
167.Vb 1
168\& s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
169.Ve
170.Sp
171into this:
172.Sp
173.Vb 10
174\& s{ < # opening angle bracket
175\& (?: # Non-backreffing grouping paren
176\& [^>'"] * # 0 or more things that are neither > nor ' nor "
177\& | # or else
178\& ".*?" # a section between double quotes (stingy match)
179\& | # or else
180\& '.*?' # a section between single quotes (stingy match)
181\& ) + # all occurring one or more times
182\& > # closing angle bracket
183\& }{}gsx; # replace with nothing, i.e. delete
184.Ve
185.Sp
186It's still not quite so clear as prose, but it is very useful for
187describing the meaning of each part of the pattern.
188.IP "Different Delimiters" 4
189.IX Item "Different Delimiters"
190While we normally think of patterns as being delimited with \f(CW\*(C`/\*(C'\fR
191characters, they can be delimited by almost any character. perlre
192describes this. For example, the \f(CW\*(C`s///\*(C'\fR above uses braces as
193delimiters. Selecting another delimiter can avoid quoting the
194delimiter within the pattern:
195.Sp
196.Vb 2
197\& s/\e/usr\e/local/\e/usr\e/share/g; # bad delimiter choice
198\& s#/usr/local#/usr/share#g; # better
199.Ve
200.Sh "I'm having trouble matching over more than one line. What's wrong?"
201.IX Subsection "I'm having trouble matching over more than one line. What's wrong?"
202Either you don't have more than one line in the string you're looking
203at (probably), or else you aren't using the correct modifier(s) on
204your pattern (possibly).
205.PP
206There are many ways to get multiline data into a string. If you want
207it to happen automatically while reading input, you'll want to set $/
208(probably to '' for paragraphs or \f(CW\*(C`undef\*(C'\fR for the whole file) to
209allow you to read more than one line at a time.
210.PP
211Read perlre to help you decide which of \f(CW\*(C`/s\*(C'\fR and \f(CW\*(C`/m\*(C'\fR (or both)
212you might want to use: \f(CW\*(C`/s\*(C'\fR allows dot to include newline, and \f(CW\*(C`/m\*(C'\fR
213allows caret and dollar to match next to a newline, not just at the
214end of the string. You do need to make sure that you've actually
215got a multiline string in there.
216.PP
217For example, this program detects duplicate words, even when they span
218line breaks (but not paragraph ones). For this example, we don't need
219\&\f(CW\*(C`/s\*(C'\fR because we aren't using dot in a regular expression that we want
220to cross line boundaries. Neither do we need \f(CW\*(C`/m\*(C'\fR because we aren't
221wanting caret or dollar to match at any point inside the record next
222to newlines. But it's imperative that $/ be set to something other
223than the default, or else we won't actually ever have a multiline
224record read in.
225.PP
226.Vb 6
227\& $/ = ''; # read in more whole paragraph, not just one line
228\& while ( <> ) {
229\& while ( /\eb([\ew'-]+)(\es+\e1)+\eb/gi ) { # word starts alpha
230\& print "Duplicate $1 at paragraph $.\en";
231\& }
232\& }
233.Ve
234.PP
235Here's code that finds sentences that begin with \*(L"From \*(R" (which would
236be mangled by many mailers):
237.PP
238.Vb 6
239\& $/ = ''; # read in more whole paragraph, not just one line
240\& while ( <> ) {
241\& while ( /^From /gm ) { # /m makes ^ match next to \en
242\& print "leading from in paragraph $.\en";
243\& }
244\& }
245.Ve
246.PP
247Here's code that finds everything between \s-1START\s0 and \s-1END\s0 in a paragraph:
248.PP
249.Vb 6
250\& undef $/; # read in whole file, not just one line or paragraph
251\& while ( <> ) {
252\& while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries
253\& print "$1\en";
254\& }
255\& }
256.Ve
257.Sh "How can I pull out lines between two patterns that are themselves on different lines?"
258.IX Subsection "How can I pull out lines between two patterns that are themselves on different lines?"
259You can use Perl's somewhat exotic \f(CW\*(C`..\*(C'\fR operator (documented in
260perlop):
261.PP
262.Vb 1
263\& perl -ne 'print if /START/ .. /END/' file1 file2 ...
264.Ve
265.PP
266If you wanted text and not lines, you would use
267.PP
268.Vb 1
269\& perl -0777 -ne 'print "$1\en" while /START(.*?)END/gs' file1 file2 ...
270.Ve
271.PP
272But if you want nested occurrences of \f(CW\*(C`START\*(C'\fR through \f(CW\*(C`END\*(C'\fR, you'll
273run up against the problem described in the question in this section
274on matching balanced text.
275.PP
276Here's another example of using \f(CW\*(C`..\*(C'\fR:
277.PP
278.Vb 7
279\& while (<>) {
280\& $in_header = 1 .. /^$/;
281\& $in_body = /^$/ .. eof();
282\& # now choose between them
283\& } continue {
284\& reset if eof(); # fix $.
285\& }
286.Ve
287.Sh "I put a regular expression into $/ but it didn't work. What's wrong?"
288.IX Subsection "I put a regular expression into $/ but it didn't work. What's wrong?"
289$/ must be a string, not a regular expression. Awk has to be better
290for something. :\-)
291.PP
292Actually, you could do this if you don't mind reading the whole file
293into memory:
294.PP
295.Vb 2
296\& undef $/;
297\& @records = split /your_pattern/, <FH>;
298.Ve
299.PP
300The Net::Telnet module (available from \s-1CPAN\s0) has the capability to
301wait for a pattern in the input stream, or timeout if it doesn't
302appear within a certain time.
303.PP
304.Vb 4
305\& ## Create a file with three lines.
306\& open FH, ">file";
307\& print FH "The first line\enThe second line\enThe third line\en";
308\& close FH;
309.Ve
310.PP
311.Vb 2
312\& ## Get a read/write filehandle to it.
313\& $fh = new IO::File "+<file";
314.Ve
315.PP
316.Vb 3
317\& ## Attach it to a "stream" object.
318\& use Net::Telnet;
319\& $file = new Net::Telnet (-fhopen => $fh);
320.Ve
321.PP
322.Vb 3
323\& ## Search for the second line and print out the third.
324\& $file->waitfor('/second line\en/');
325\& print $file->getline;
326.Ve
327.Sh "How do I substitute case insensitively on the \s-1LHS\s0 while preserving case on the \s-1RHS\s0?"
328.IX Subsection "How do I substitute case insensitively on the LHS while preserving case on the RHS?"
329Here's a lovely Perlish solution by Larry Rosler. It exploits
330properties of bitwise xor on \s-1ASCII\s0 strings.
331.PP
332.Vb 1
333\& $_= "this is a TEsT case";
334.Ve
335.PP
336.Vb 2
337\& $old = 'test';
338\& $new = 'success';
339.Ve
340.PP
341.Vb 5
342\& s{(\eQ$old\eE)}
343\& { uc $new | (uc $1 ^ $1) .
344\& (uc(substr $1, -1) ^ substr $1, -1) x
345\& (length($new) - length $1)
346\& }egi;
347.Ve
348.PP
349.Vb 1
350\& print;
351.Ve
352.PP
353And here it is as a subroutine, modeled after the above:
354.PP
355.Vb 3
356\& sub preserve_case($$) {
357\& my ($old, $new) = @_;
358\& my $mask = uc $old ^ $old;
359.Ve
360.PP
361.Vb 3
362\& uc $new | $mask .
363\& substr($mask, -1) x (length($new) - length($old))
364\& }
365.Ve
366.PP
367.Vb 3
368\& $a = "this is a TEsT case";
369\& $a =~ s/(test)/preserve_case($1, "success")/egi;
370\& print "$a\en";
371.Ve
372.PP
373This prints:
374.PP
375.Vb 1
376\& this is a SUcCESS case
377.Ve
378.PP
379As an alternative, to keep the case of the replacement word if it is
380longer than the original, you can use this code, by Jeff Pinyan:
381.PP
382.Vb 3
383\& sub preserve_case {
384\& my ($from, $to) = @_;
385\& my ($lf, $lt) = map length, @_;
386.Ve
387.PP
388.Vb 2
389\& if ($lt < $lf) { $from = substr $from, 0, $lt }
390\& else { $from .= substr $to, $lf }
391.Ve
392.PP
393.Vb 2
394\& return uc $to | ($from ^ uc $from);
395\& }
396.Ve
397.PP
398This changes the sentence to \*(L"this is a SUcCess case.\*(R"
399.PP
400Just to show that C programmers can write C in any programming language,
401if you prefer a more C\-like solution, the following script makes the
402substitution have the same case, letter by letter, as the original.
403(It also happens to run about 240% slower than the Perlish solution runs.)
404If the substitution has more characters than the string being substituted,
405the case of the last character is used for the rest of the substitution.
406.PP
407.Vb 8
408\& # Original by Nathan Torkington, massaged by Jeffrey Friedl
409\& #
410\& sub preserve_case($$)
411\& {
412\& my ($old, $new) = @_;
413\& my ($state) = 0; # 0 = no change; 1 = lc; 2 = uc
414\& my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new));
415\& my ($len) = $oldlen < $newlen ? $oldlen : $newlen;
416.Ve
417.PP
418.Vb 21
419\& for ($i = 0; $i < $len; $i++) {
420\& if ($c = substr($old, $i, 1), $c =~ /[\eW\ed_]/) {
421\& $state = 0;
422\& } elsif (lc $c eq $c) {
423\& substr($new, $i, 1) = lc(substr($new, $i, 1));
424\& $state = 1;
425\& } else {
426\& substr($new, $i, 1) = uc(substr($new, $i, 1));
427\& $state = 2;
428\& }
429\& }
430\& # finish up with any remaining new (for when new is longer than old)
431\& if ($newlen > $oldlen) {
432\& if ($state == 1) {
433\& substr($new, $oldlen) = lc(substr($new, $oldlen));
434\& } elsif ($state == 2) {
435\& substr($new, $oldlen) = uc(substr($new, $oldlen));
436\& }
437\& }
438\& return $new;
439\& }
440.Ve
441.ie n .Sh "How can I make ""\ew"" match national character sets?"
442.el .Sh "How can I make \f(CW\ew\fP match national character sets?"
443.IX Subsection "How can I make w match national character sets?"
444See perllocale.
445.ie n .Sh "How can I match a locale-smart version of ""/[a\-zA\-Z]/""?"
446.el .Sh "How can I match a locale-smart version of \f(CW/[a\-zA\-Z]/\fP?"
447.IX Subsection "How can I match a locale-smart version of /[a-zA-Z]/?"
448One alphabetic character would be \f(CW\*(C`/[^\eW\ed_]/\*(C'\fR, no matter what locale
449you're in. Non-alphabetics would be \f(CW\*(C`/[\eW\ed_]/\*(C'\fR (assuming you don't
450consider an underscore a letter).
451.Sh "How can I quote a variable to use in a regex?"
452.IX Subsection "How can I quote a variable to use in a regex?"
453The Perl parser will expand \f(CW$variable\fR and \f(CW@variable\fR references in
454regular expressions unless the delimiter is a single quote. Remember,
455too, that the right-hand side of a \f(CW\*(C`s///\*(C'\fR substitution is considered
456a double-quoted string (see perlop for more details). Remember
457also that any regex special characters will be acted on unless you
458precede the substitution with \eQ. Here's an example:
459.PP
460.Vb 3
461\& $string = "to die?";
462\& $lhs = "die?";
463\& $rhs = "sleep, no more";
464.Ve
465.PP
466.Vb 2
467\& $string =~ s/\eQ$lhs/$rhs/;
468\& # $string is now "to sleep no more"
469.Ve
470.PP
471Without the \eQ, the regex would also spuriously match \*(L"di\*(R".
472.ie n .Sh "What is ""/o"" really for?"
473.el .Sh "What is \f(CW/o\fP really for?"
474.IX Subsection "What is /o really for?"
475Using a variable in a regular expression match forces a re-evaluation
476(and perhaps recompilation) each time the regular expression is
477encountered. The \f(CW\*(C`/o\*(C'\fR modifier locks in the regex the first time
478it's used. This always happens in a constant regular expression, and
479in fact, the pattern was compiled into the internal format at the same
480time your entire program was.
481.PP
482Use of \f(CW\*(C`/o\*(C'\fR is irrelevant unless variable interpolation is used in
483the pattern, and if so, the regex engine will neither know nor care
484whether the variables change after the pattern is evaluated the \fIvery
485first\fR time.
486.PP
487\&\f(CW\*(C`/o\*(C'\fR is often used to gain an extra measure of efficiency by not
488performing subsequent evaluations when you know it won't matter
489(because you know the variables won't change), or more rarely, when
490you don't want the regex to notice if they do.
491.PP
492For example, here's a \*(L"paragrep\*(R" program:
493.PP
494.Vb 5
495\& $/ = ''; # paragraph mode
496\& $pat = shift;
497\& while (<>) {
498\& print if /$pat/o;
499\& }
500.Ve
501.Sh "How do I use a regular expression to strip C style comments from a file?"
502.IX Subsection "How do I use a regular expression to strip C style comments from a file?"
503While this actually can be done, it's much harder than you'd think.
504For example, this one-liner
505.PP
506.Vb 1
507\& perl -0777 -pe 's{/\e*.*?\e*/}{}gs' foo.c
508.Ve
509.PP
510will work in many but not all cases. You see, it's too simple-minded for
511certain kinds of C programs, in particular, those with what appear to be
512comments in quoted strings. For that, you'd need something like this,
513created by Jeffrey Friedl and later modified by Fred Curtis.
514.PP
515.Vb 4
516\& $/ = undef;
517\& $_ = <>;
518\& s#/\e*[^*]*\e*+([^/*][^*]*\e*+)*/|("(\e\e.|[^"\e\e])*"|'(\e\e.|[^'\e\e])*'|.[^/"'\e\e]*)#$2#gs
519\& print;
520.Ve
521.PP
522This could, of course, be more legibly written with the \f(CW\*(C`/x\*(C'\fR modifier, adding
523whitespace and comments. Here it is expanded, courtesy of Fred Curtis.
524.PP
525.Vb 8
526\& s{
527\& /\e* ## Start of /* ... */ comment
528\& [^*]*\e*+ ## Non-* followed by 1-or-more *'s
529\& (
530\& [^/*][^*]*\e*+
531\& )* ## 0-or-more things which don't start with /
532\& ## but do end with '*'
533\& / ## End of /* ... */ comment
534.Ve
535.PP
536.Vb 1
537\& | ## OR various things which aren't comments:
538.Ve
539.PP
540.Vb 8
541\& (
542\& " ## Start of " ... " string
543\& (
544\& \e\e. ## Escaped char
545\& | ## OR
546\& [^"\e\e] ## Non "\e
547\& )*
548\& " ## End of " ... " string
549.Ve
550.PP
551.Vb 1
552\& | ## OR
553.Ve
554.PP
555.Vb 7
556\& ' ## Start of ' ... ' string
557\& (
558\& \e\e. ## Escaped char
559\& | ## OR
560\& [^'\e\e] ## Non '\e
561\& )*
562\& ' ## End of ' ... ' string
563.Ve
564.PP
565.Vb 1
566\& | ## OR
567.Ve
568.PP
569.Vb 4
570\& . ## Anything other char
571\& [^/"'\e\e]* ## Chars which doesn't start a comment, string or escape
572\& )
573\& }{$2}gxs;
574.Ve
575.PP
576A slight modification also removes \*(C+ comments:
577.PP
578.Vb 1
579\& s#/\e*[^*]*\e*+([^/*][^*]*\e*+)*/|//[^\en]*|("(\e\e.|[^"\e\e])*"|'(\e\e.|[^'\e\e])*'|.[^/"'\e\e]*)#$2#gs;
580.Ve
581.Sh "Can I use Perl regular expressions to match balanced text?"
582.IX Subsection "Can I use Perl regular expressions to match balanced text?"
583Historically, Perl regular expressions were not capable of matching
584balanced text. As of more recent versions of perl including 5.6.1
585experimental features have been added that make it possible to do this.
586Look at the documentation for the (??{ }) construct in recent perlre manual
587pages to see an example of matching balanced parentheses. Be sure to take
588special notice of the warnings present in the manual before making use
589of this feature.
590.PP
591\&\s-1CPAN\s0 contains many modules that can be useful for matching text
592depending on the context. Damian Conway provides some useful
593patterns in Regexp::Common. The module Text::Balanced provides a
594general solution to this problem.
595.PP
596One of the common applications of balanced text matching is working
597with \s-1XML\s0 and \s-1HTML\s0. There are many modules available that support
598these needs. Two examples are HTML::Parser and XML::Parser. There
599are many others.
600.PP
601An elaborate subroutine (for 7\-bit \s-1ASCII\s0 only) to pull out balanced
602and possibly nested single chars, like \f(CW\*(C``\*(C'\fR and \f(CW\*(C`'\*(C'\fR, \f(CW\*(C`{\*(C'\fR and \f(CW\*(C`}\*(C'\fR,
603or \f(CW\*(C`(\*(C'\fR and \f(CW\*(C`)\*(C'\fR can be found in
604http://www.cpan.org/authors/id/TOMC/scripts/pull_quotes.gz .
605.PP
606The C::Scan module from \s-1CPAN\s0 also contains such subs for internal use,
607but they are undocumented.
608.Sh "What does it mean that regexes are greedy? How can I get around it?"
609.IX Subsection "What does it mean that regexes are greedy? How can I get around it?"
610Most people mean that greedy regexes match as much as they can.
611Technically speaking, it's actually the quantifiers (\f(CW\*(C`?\*(C'\fR, \f(CW\*(C`*\*(C'\fR, \f(CW\*(C`+\*(C'\fR,
612\&\f(CW\*(C`{}\*(C'\fR) that are greedy rather than the whole pattern; Perl prefers local
613greed and immediate gratification to overall greed. To get non-greedy
614versions of the same quantifiers, use (\f(CW\*(C`??\*(C'\fR, \f(CW\*(C`*?\*(C'\fR, \f(CW\*(C`+?\*(C'\fR, \f(CW\*(C`{}?\*(C'\fR).
615.PP
616An example:
617.PP
618.Vb 3
619\& $s1 = $s2 = "I am very very cold";
620\& $s1 =~ s/ve.*y //; # I am cold
621\& $s2 =~ s/ve.*?y //; # I am very cold
622.Ve
623.PP
624Notice how the second substitution stopped matching as soon as it
625encountered \*(L"y \*(R". The \f(CW\*(C`*?\*(C'\fR quantifier effectively tells the regular
626expression engine to find a match as quickly as possible and pass
627control on to whatever is next in line, like you would if you were
628playing hot potato.
629.Sh "How do I process each word on each line?"
630.IX Subsection "How do I process each word on each line?"
631Use the split function:
632.PP
633.Vb 5
634\& while (<>) {
635\& foreach $word ( split ) {
636\& # do something with $word here
637\& }
638\& }
639.Ve
640.PP
641Note that this isn't really a word in the English sense; it's just
642chunks of consecutive non-whitespace characters.
643.PP
644To work with only alphanumeric sequences (including underscores), you
645might consider
646.PP
647.Vb 5
648\& while (<>) {
649\& foreach $word (m/(\ew+)/g) {
650\& # do something with $word here
651\& }
652\& }
653.Ve
654.Sh "How can I print out a word-frequency or line-frequency summary?"
655.IX Subsection "How can I print out a word-frequency or line-frequency summary?"
656To do this, you have to parse out each word in the input stream. We'll
657pretend that by word you mean chunk of alphabetics, hyphens, or
658apostrophes, rather than the non-whitespace chunk idea of a word given
659in the previous question:
660.PP
661.Vb 8
662\& while (<>) {
663\& while ( /(\eb[^\eW_\ed][\ew'-]+\eb)/g ) { # misses "`sheep'"
664\& $seen{$1}++;
665\& }
666\& }
667\& while ( ($word, $count) = each %seen ) {
668\& print "$count $word\en";
669\& }
670.Ve
671.PP
672If you wanted to do the same thing for lines, you wouldn't need a
673regular expression:
674.PP
675.Vb 6
676\& while (<>) {
677\& $seen{$_}++;
678\& }
679\& while ( ($line, $count) = each %seen ) {
680\& print "$count $line";
681\& }
682.Ve
683.PP
684If you want these output in a sorted order, see perlfaq4: ``How do I
685sort a hash (optionally by value instead of key)?''.
686.Sh "How can I do approximate matching?"
687.IX Subsection "How can I do approximate matching?"
688See the module String::Approx available from \s-1CPAN\s0.
689.Sh "How do I efficiently match many regular expressions at once?"
690.IX Subsection "How do I efficiently match many regular expressions at once?"
691The following is extremely inefficient:
692.PP
693.Vb 10
694\& # slow but obvious way
695\& @popstates = qw(CO ON MI WI MN);
696\& while (defined($line = <>)) {
697\& for $state (@popstates) {
698\& if ($line =~ /\eb$state\eb/i) {
699\& print $line;
700\& last;
701\& }
702\& }
703\& }
704.Ve
705.PP
706That's because Perl has to recompile all those patterns for each of
707the lines of the file. As of the 5.005 release, there's a much better
708approach, one which makes use of the new \f(CW\*(C`qr//\*(C'\fR operator:
709.PP
710.Vb 9
711\& # use spiffy new qr// operator, with /i flag even
712\& use 5.005;
713\& @popstates = qw(CO ON MI WI MN);
714\& @poppats = map { qr/\eb$_\eb/i } @popstates;
715\& while (defined($line = <>)) {
716\& for $patobj (@poppats) {
717\& print $line if $line =~ /$patobj/;
718\& }
719\& }
720.Ve
721.ie n .Sh "Why don't word-boundary searches with ""\eb"" work for me?"
722.el .Sh "Why don't word-boundary searches with \f(CW\eb\fP work for me?"
723.IX Subsection "Why don't word-boundary searches with b work for me?"
724Two common misconceptions are that \f(CW\*(C`\eb\*(C'\fR is a synonym for \f(CW\*(C`\es+\*(C'\fR and
725that it's the edge between whitespace characters and non-whitespace
726characters. Neither is correct. \f(CW\*(C`\eb\*(C'\fR is the place between a \f(CW\*(C`\ew\*(C'\fR
727character and a \f(CW\*(C`\eW\*(C'\fR character (that is, \f(CW\*(C`\eb\*(C'\fR is the edge of a
728\&\*(L"word\*(R"). It's a zero-width assertion, just like \f(CW\*(C`^\*(C'\fR, \f(CW\*(C`$\*(C'\fR, and all
729the other anchors, so it doesn't consume any characters. perlre
730describes the behavior of all the regex metacharacters.
731.PP
732Here are examples of the incorrect application of \f(CW\*(C`\eb\*(C'\fR, with fixes:
733.PP
734.Vb 2
735\& "two words" =~ /(\ew+)\eb(\ew+)/; # WRONG
736\& "two words" =~ /(\ew+)\es+(\ew+)/; # right
737.Ve
738.PP
739.Vb 2
740\& " =matchless= text" =~ /\eb=(\ew+)=\eb/; # WRONG
741\& " =matchless= text" =~ /=(\ew+)=/; # right
742.Ve
743.PP
744Although they may not do what you thought they did, \f(CW\*(C`\eb\*(C'\fR and \f(CW\*(C`\eB\*(C'\fR
745can still be quite useful. For an example of the correct use of
746\&\f(CW\*(C`\eb\*(C'\fR, see the example of matching duplicate words over multiple
747lines.
748.PP
749An example of using \f(CW\*(C`\eB\*(C'\fR is the pattern \f(CW\*(C`\eBis\eB\*(C'\fR. This will find
750occurrences of \*(L"is\*(R" on the insides of words only, as in \*(L"thistle\*(R", but
751not \*(L"this\*(R" or \*(L"island\*(R".
752.Sh "Why does using $&, $`, or $' slow my program down?"
753.IX Subsection "Why does using $&, $`, or $' slow my program down?"
754Once Perl sees that you need one of these variables anywhere in
755the program, it provides them on each and every pattern match.
756The same mechanism that handles these provides for the use of \f(CW$1\fR, \f(CW$2\fR,
757etc., so you pay the same price for each regex that contains capturing
758parentheses. If you never use $&, etc., in your script, then regexes
759\&\fIwithout\fR capturing parentheses won't be penalized. So avoid $&, $',
760and $` if you can, but if you can't, once you've used them at all, use
761them at will because you've already paid the price. Remember that some
762algorithms really appreciate them. As of the 5.005 release. the $&
763variable is no longer \*(L"expensive\*(R" the way the other two are.
764.ie n .Sh "What good is ""\eG"" in a regular expression?"
765.el .Sh "What good is \f(CW\eG\fP in a regular expression?"
766.IX Subsection "What good is G in a regular expression?"
767The notation \f(CW\*(C`\eG\*(C'\fR is used in a match or substitution in conjunction with
768the \f(CW\*(C`/g\*(C'\fR modifier to anchor the regular expression to the point just past
769where the last match occurred, i.e. the \fIpos()\fR point. A failed match resets
770the position of \f(CW\*(C`\eG\*(C'\fR unless the \f(CW\*(C`/c\*(C'\fR modifier is in effect. \f(CW\*(C`\eG\*(C'\fR can be
771used in a match without the \f(CW\*(C`/g\*(C'\fR modifier; it acts the same (i.e. still
772anchors at the \fIpos()\fR point) but of course only matches once and does not
773update \fIpos()\fR, as non\-\f(CW\*(C`/g\*(C'\fR expressions never do. \f(CW\*(C`\eG\*(C'\fR in an expression
774applied to a target string that has never been matched against a \f(CW\*(C`/g\*(C'\fR
775expression before or has had its \fIpos()\fR reset is functionally equivalent to
776\&\f(CW\*(C`\eA\*(C'\fR, which matches at the beginning of the string.
777.PP
778For example, suppose you had a line of text quoted in standard mail
779and Usenet notation, (that is, with leading \f(CW\*(C`>\*(C'\fR characters), and
780you want change each leading \f(CW\*(C`>\*(C'\fR into a corresponding \f(CW\*(C`:\*(C'\fR. You
781could do so in this way:
782.PP
783.Vb 1
784\& s/^(>+)/':' x length($1)/gem;
785.Ve
786.PP
787Or, using \f(CW\*(C`\eG\*(C'\fR, the much simpler (and faster):
788.PP
789.Vb 1
790\& s/\eG>/:/g;
791.Ve
792.PP
793A more sophisticated use might involve a tokenizer. The following
794lex-like example is courtesy of Jeffrey Friedl. It did not work in
7955.003 due to bugs in that release, but does work in 5.004 or better.
796(Note the use of \f(CW\*(C`/c\*(C'\fR, which prevents a failed match with \f(CW\*(C`/g\*(C'\fR from
797resetting the search position back to the beginning of the string.)
798.PP
799.Vb 9
800\& while (<>) {
801\& chomp;
802\& PARSER: {
803\& m/ \eG( \ed+\eb )/gcx && do { print "number: $1\en"; redo; };
804\& m/ \eG( \ew+ )/gcx && do { print "word: $1\en"; redo; };
805\& m/ \eG( \es+ )/gcx && do { print "space: $1\en"; redo; };
806\& m/ \eG( [^\ew\ed]+ )/gcx && do { print "other: $1\en"; redo; };
807\& }
808\& }
809.Ve
810.PP
811Of course, that could have been written as
812.PP
813.Vb 21
814\& while (<>) {
815\& chomp;
816\& PARSER: {
817\& if ( /\eG( \ed+\eb )/gcx {
818\& print "number: $1\en";
819\& redo PARSER;
820\& }
821\& if ( /\eG( \ew+ )/gcx {
822\& print "word: $1\en";
823\& redo PARSER;
824\& }
825\& if ( /\eG( \es+ )/gcx {
826\& print "space: $1\en";
827\& redo PARSER;
828\& }
829\& if ( /\eG( [^\ew\ed]+ )/gcx {
830\& print "other: $1\en";
831\& redo PARSER;
832\& }
833\& }
834\& }
835.Ve
836.PP
837but then you lose the vertical alignment of the regular expressions.
838.Sh "Are Perl regexes DFAs or NFAs? Are they \s-1POSIX\s0 compliant?"
839.IX Subsection "Are Perl regexes DFAs or NFAs? Are they POSIX compliant?"
840While it's true that Perl's regular expressions resemble the DFAs
841(deterministic finite automata) of the \fIegrep\fR\|(1) program, they are in
842fact implemented as NFAs (non\-deterministic finite automata) to allow
843backtracking and backreferencing. And they aren't POSIX-style either,
844because those guarantee worst-case behavior for all cases. (It seems
845that some people prefer guarantees of consistency, even when what's
846guaranteed is slowness.) See the book \*(L"Mastering Regular Expressions\*(R"
847(from O'Reilly) by Jeffrey Friedl for all the details you could ever
848hope to know on these matters (a full citation appears in
849perlfaq2).
850.Sh "What's wrong with using grep or map in a void context?"
851.IX Subsection "What's wrong with using grep or map in a void context?"
852The problem is that both grep and map build a return list,
853regardless of the context. This means you're making Perl go
854to the trouble of building a list that you then just throw away.
855If the list is large, you waste both time and space. If your
856intent is to iterate over the list then use a for loop for this
857purpose.
858.Sh "How can I match strings with multibyte characters?"
859.IX Subsection "How can I match strings with multibyte characters?"
860Starting from Perl 5.6 Perl has had some level of multibyte character
861support. Perl 5.8 or later is recommended. Supported multibyte
862character repertoires include Unicode, and legacy encodings
863through the Encode module. See perluniintro, perlunicode,
864and Encode.
865.PP
866If you are stuck with older Perls, you can do Unicode with the
867\&\f(CW\*(C`Unicode::String\*(C'\fR module, and character conversions using the
868\&\f(CW\*(C`Unicode::Map8\*(C'\fR and \f(CW\*(C`Unicode::Map\*(C'\fR modules. If you are using
869Japanese encodings, you might try using the jperl 5.005_03.
870.PP
871Finally, the following set of approaches was offered by Jeffrey
872Friedl, whose article in issue #5 of The Perl Journal talks about
873this very matter.
874.PP
875Let's suppose you have some weird Martian encoding where pairs of
876\&\s-1ASCII\s0 uppercase letters encode single Martian letters (i.e. the two
877bytes \*(L"\s-1CV\s0\*(R" make a single Martian letter, as do the two bytes \*(L"\s-1SG\s0\*(R",
878\&\*(L"\s-1VS\s0\*(R", \*(L"\s-1XX\s0\*(R", etc.). Other bytes represent single characters, just like
879\&\s-1ASCII\s0.
880.PP
881So, the string of Martian \*(L"I am \s-1CVSGXX\s0!\*(R" uses 12 bytes to encode the
882nine characters 'I', ' ', 'a', 'm', ' ', '\s-1CV\s0', '\s-1SG\s0', '\s-1XX\s0', '!'.
883.PP
884Now, say you want to search for the single character \f(CW\*(C`/GX/\*(C'\fR. Perl
885doesn't know about Martian, so it'll find the two bytes \*(L"\s-1GX\s0\*(R" in the \*(L"I
886am \s-1CVSGXX\s0!\*(R" string, even though that character isn't there: it just
887looks like it is because \*(L"\s-1SG\s0\*(R" is next to \*(L"\s-1XX\s0\*(R", but there's no real
888\&\*(L"\s-1GX\s0\*(R". This is a big problem.
889.PP
890Here are a few ways, all painful, to deal with it:
891.PP
892.Vb 3
893\& $martian =~ s/([A-Z][A-Z])/ $1 /g; # Make sure adjacent ``martian'' bytes
894\& # are no longer adjacent.
895\& print "found GX!\en" if $martian =~ /GX/;
896.Ve
897.PP
898Or like this:
899.PP
900.Vb 6
901\& @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
902\& # above is conceptually similar to: @chars = $text =~ m/(.)/g;
903\& #
904\& foreach $char (@chars) {
905\& print "found GX!\en", last if $char eq 'GX';
906\& }
907.Ve
908.PP
909Or like this:
910.PP
911.Vb 3
912\& while ($martian =~ m/\eG([A-Z][A-Z]|.)/gs) { # \eG probably unneeded
913\& print "found GX!\en", last if $1 eq 'GX';
914\& }
915.Ve
916.PP
917Or like this:
918.PP
919.Vb 1
920\& die "sorry, Perl doesn't (yet) have Martian support )-:\en";
921.Ve
922.PP
923There are many double\- (and multi\-) byte encodings commonly used these
924days. Some versions of these have 1\-, 2\-, 3\-, and 4\-byte characters,
925all mixed.
926.Sh "How do I match a pattern that is supplied by the user?"
927.IX Subsection "How do I match a pattern that is supplied by the user?"
928Well, if it's really a pattern, then just use
929.PP
930.Vb 2
931\& chomp($pattern = <STDIN>);
932\& if ($line =~ /$pattern/) { }
933.Ve
934.PP
935Alternatively, since you have no guarantee that your user entered
936a valid regular expression, trap the exception this way:
937.PP
938.Vb 1
939\& if (eval { $line =~ /$pattern/ }) { }
940.Ve
941.PP
942If all you really want to search for a string, not a pattern,
943then you should either use the \fIindex()\fR function, which is made for
944string searching, or if you can't be disabused of using a pattern
945match on a non\-pattern, then be sure to use \f(CW\*(C`\eQ\*(C'\fR...\f(CW\*(C`\eE\*(C'\fR, documented
946in perlre.
947.PP
948.Vb 1
949\& $pattern = <STDIN>;
950.Ve
951.PP
952.Vb 5
953\& open (FILE, $input) or die "Couldn't open input $input: $!; aborting";
954\& while (<FILE>) {
955\& print if /\eQ$pattern\eE/;
956\& }
957\& close FILE;
958.Ve
959.SH "AUTHOR AND COPYRIGHT"
960.IX Header "AUTHOR AND COPYRIGHT"
961Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
962All rights reserved.
963.PP
964This documentation is free; you can redistribute it and/or modify it
965under the same terms as Perl itself.
966.PP
967Irrespective of its distribution, all code examples in this file
968are hereby placed into the public domain. You are permitted and
969encouraged to use this code in your own programs for fun
970or for profit as you see fit. A simple comment in the code giving
971credit would be courteous but is not required.