File: perlfaq6.html

package info (click to toggle)
perl-doc-html 5.26.0-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 39,400 kB
  • sloc: xml: 36; makefile: 7
file content (1081 lines) | stat: -rw-r--r-- 110,639 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title>perlfaq6 - perldoc.perl.org</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta http-equiv="Content-Language" content="en-gb">
  <link rel="search" type="application/opensearchdescription+xml" title="Search perldoc.perl.org" href="/static/search.xml"/>
  <link href="static/css-20100830.css" rel="stylesheet" rev="stylesheet" type="text/css" media="screen">
  <link href="static/exploreperl.css" rel="stylesheet" rev="stylesheet" type="text/css">
</head>

<body onLoad="perldoc.startup();" onPageShow="if (event.persisted) perldoc.startup();">
    <div id="page">
      
      <div id="header">
	<div id="homepage_link">
	  <a href="index.html"></a>
	</div>
	<div id="strapline">
	  Perl Programming Documentation
	</div>
	<div id="download_link" class="download">
	  <a href="http://www.perl.org/get.html">Download Perl</a>
	</div>
	<div id="explore_link" class="download">
	  <a id="explore_anchor" href="#">Explore</a>
	</div>
      </div>
      
      <div id="body">
        <div id="left_column">
          <div class="side_group">
            
	    <div class="side_panel doc_panel">
              <p>Manual</p>
              <ul>
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">History / Changes</a>
                <li><a href="index-licence.html">License</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Reference</p>
              <ul>
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Special Variables</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platform Specific</a>
              </ul>
            </div>
            <div class="side_panel doc_panel">
              <p>Modules</p>
              <ul>
		<li>
		
                
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		    
		  
		
                  
		
                  
		
                  
		    
		  
		
                  
		
                  
		
		
                    <a href="index-modules-A.html">A</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-B.html">B</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-C.html">C</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-D.html">D</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-E.html">E</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-F.html">F</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-G.html">G</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-H.html">H</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-I.html">I</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-L.html">L</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-M.html">M</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-N.html">N</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-O.html">O</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-P.html">P</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-S.html">S</a>
                    
                      
                        <li>
                      
                    
                
                    <a href="index-modules-T.html">T</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-U.html">U</a>
                    
                      
                        &bull;
                      
                    
                
                    <a href="index-modules-X.html">X</a>
                    
                
              </ul>
            </div>
            
	      <div class="side_panel doc_panel">
		<p>Tools</p>
		<ul>
		  <li><a href="preferences.html">Preferences</a>
		</ul>
	      </div>
            
          </div>
        </div>
        <div id="centre_column">
          <div id="content_header">
            <div id="title_bar">
              <div id="page_name">
                <h1>perlfaq6</h1>
              </div>
              <div id="perl_version">
                Perl 5 version 26.0 documentation
              </div>
              <div class="page_links" id="page_links_top">
                <a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
		
              </div>
	      <div class="page_links" id="page_links_bottom">
		
                  <a href="#" id="page_index_toggle">Show page index</a> &bull;
		
                <a href="#" id="recent_pages_toggle">Show recent pages</a>		
	      </div>
	      <div id="search_form">
		<form action="search.html" method="GET" id="search">
		  <input type="text" name="q" id="search_box" alt="Search">
		</form>
	      </div>
            </div>
            <div id="breadcrumbs">
                
    <a href="index.html">Home</a> &gt;
    
      
        <a href="index-faq.html">FAQs</a> &gt;
      
    
    perlfaq6
  

            </div>
          </div>
          <div id="content_body">
	    <!--[if lt IE 7]>
 <div class="noscript">
   <p>
     <strong>It looks like you're using Internet Explorer 6. This is a very old
     browser which does not offer full support for modern websites.</strong>
   </p>
   <p>
     Unfortunately this means that this website will not work on
     your computer.
   </p>
   <p>
     Don't miss out though! To view the site (and get a better experience from
     many other websites), simply upgrade to
     <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet
Explorer 8</a>
     or download an alternative browser such as
     <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>,
     <a href="http://www.apple.com/safari/download/">Safari</a>, or
     <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
   </p>
   <p>
     All of these browsers are free. If you're using a PC at work, you may
     need to contact your IT administrator.
   </p>
 </div>
<![endif]-->
	    <noscript>
	      <div class="noscript">
	      <p>
                <strong>Please note: Many features of this site require JavaScript. You appear to have JavaScript disabled,
	        or are running a non-JavaScript capable web browser.</strong>
	      </p>
	      <p>
		To get the best experience, please enable JavaScript or download a modern web browser such as <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet Explorer 8</a>, <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, or <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
              </p>
	      </div>
	    </noscript>

	    <div id="recent_pages" class="hud_container">
	      <div id="recent_pages_header" class="hud_header">
		<div id="recent_pages_close" class="hud_close"><a href="#" onClick="recentPages.hide();return false;"></a></div>
		<div id="recent_pages_title" class="hud_title"><span class="hud_span_top">Recently read</span></div>
		<div id="recent_pages_topright" class="hud_topright"></div>
	      </div>
	      <div id="recent_pages_content" class="hud_content">
	      </div>
	      <div id="recent_pages_footer" class="hud_footer">
		<div id="recent_pages_bottomleft" class="hud_bottomleft"></div>
		<div id="recent_pages_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
		<div id="recent_pages_resize" class="hud_resize"></div>
	      </div>
	    </div>
  
	    <div id="from_search"></div>
            <h1>perlfaq6</h1>


  <!--    -->
<ul><li><a href="#NAME">NAME</a><li><a href="#VERSION">VERSION</a><li><a href="#DESCRIPTION">DESCRIPTION</a><ul><li><a href="#How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code%3f">How can I hope to use regular expressions without creating illegible and unmaintainable code?
 
 </a><li><a href="#I'm-having-trouble-matching-over-more-than-one-line.-What's-wrong%3f">I'm having trouble matching over more than one line. What's wrong?
  </a><li><a href="#How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines%3f">How can I pull out lines between two patterns that are themselves on different lines?
</a><li><a href="#How-do-I-match-XML%2c-HTML%2c-or-other-nasty%2c-ugly-things-with-a-regex%3f">How do I match XML, HTML, or other nasty, ugly things with a regex?
     
</a><li><a href="#I-put-a-regular-expression-into-%24%2f-but-it-didn't-work.-What's-wrong%3f">I put a regular expression into $/ but it didn't work. What's wrong?
 
</a><li><a href="#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS%3f">How do I substitute case-insensitively on the LHS while preserving case on the RHS?
 
 </a><li><a href="#How-can-I-make-%5cw-match-national-character-sets%3f">How can I make \w match national character sets?
</a><li><a href="#How-can-I-match-a-locale-smart-version-of-%2f%5ba-zA-Z%5d%2f%3f">How can I match a locale-smart version of /[a-zA-Z]/?
</a><li><a href="#How-can-I-quote-a-variable-to-use-in-a-regex%3f">How can I quote a variable to use in a regex?
  </a><li><a href="#What-is-%2fo-really-for%3f">What is /o really for?
 </a><li><a href="#How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file%3f">How do I use a regular expression to strip C-style comments from a file?</a><li><a href="#Can-I-use-Perl-regular-expressions-to-match-balanced-text%3f">Can I use Perl regular expressions to match balanced text?
 
  
   </a><li><a href="#What-does-it-mean-that-regexes-are-greedy%3f-How-can-I-get-around-it%3f">What does it mean that regexes are greedy? How can I get around it?
 </a><li><a href="#How-do-I-process-each-word-on-each-line%3f">How do I process each word on each line?
</a><li><a href="#How-can-I-print-out-a-word-frequency-or-line-frequency-summary%3f">How can I print out a word-frequency or line-frequency summary?</a><li><a href="#How-can-I-do-approximate-matching%3f">How can I do approximate matching?
 </a><li><a href="#How-do-I-efficiently-match-many-regular-expressions-at-once%3f">How do I efficiently match many regular expressions at once?
 
</a><li><a href="#Why-don't-word-boundary-searches-with-%5cb-work-for-me%3f">Why don't word-boundary searches with \b work for me?
</a><li><a href="#Why-does-using-%24%26%2c-%24%60%2c-or-%24'-slow-my-program-down%3f">Why does using $&, $`, or $' slow my program down?
     </a><li><a href="#What-good-is-%5cG-in-a-regular-expression%3f">What good is \G in a regular expression?
</a><li><a href="#Are-Perl-regexes-DFAs-or-NFAs%3f-Are-they-POSIX-compliant%3f">Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
  </a><li><a href="#What's-wrong-with-using-grep-in-a-void-context%3f">What's wrong with using grep in a void context?
</a><li><a href="#How-can-I-match-strings-with-multibyte-characters%3f">How can I match strings with multibyte characters?
 
  </a><li><a href="#How-do-I-match-a-regular-expression-that's-in-a-variable%3f">How do I match a regular expression that's in a variable?
    
 </a></ul><li><a href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlfaq6 - Regular Expressions</p>
<a name="VERSION"></a><h1>VERSION</h1>
<p>version 5.021011</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>This section is surprisingly small because the rest of the FAQ is
littered with answers involving regular expressions. For example,
decoding a URL and checking whether something is a number can be handled
with regular expressions, but those answers are found elsewhere in
this document (in <a href="perlfaq9.html">perlfaq9</a>: "How do I decode or create those %-encodings
on the web" and <a href="perlfaq4.html">perlfaq4</a>: "How do I determine whether a scalar is
a number/whole/integer/float", to be precise).</p>
<a name="How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code%3f"></a><h2>How can I hope to use regular expressions without creating illegible and unmaintainable code?
 
 </h2>
<p>Three techniques can make regular expressions maintainable and
understandable.</p>
<ul>
<li><a name="Comments-Outside-the-Regex"></a><b>Comments Outside the Regex</b>
<p>Describe what you're doing and how you're doing it, using normal Perl
comments.</p>
<pre class="verbatim"><ol><li>    <span class="c"># turn the line into the first word, a colon, and the</span></li><li>    <span class="c"># number of characters on the rest of the line</span></li><li>    <span class="q">s/^(\w+)(.*)/ lc($1) . &quot;:&quot; . length($2) /meg</span><span class="sc">;</span></li></ol></pre></li>
<li><a name="Comments-Inside-the-Regex"></a><b>Comments Inside the Regex</b>
<p>The <code class="inline">/x</code> modifier causes whitespace to be ignored in a regex pattern
(except in a character class and a few other places), and also allows you to
use normal comments there, too. As you can imagine, whitespace and comments
help a lot.</p>
<p><code class="inline">/x</code> lets you turn this:</p>
<pre class="verbatim"><ol><li>    <span class="q">s{&lt;(?:[^&gt;&#39;&quot;]*|&quot;.*?&quot;|&#39;.*?&#39;)+&gt;}{}gs</span><span class="sc">;</span></li></ol></pre><p>into this:</p>
<pre class="verbatim"><ol><li>    <span class="q">s{ &lt;                    # opening angle bracket</span></li><li>        <span class="q">        (?:                 # Non-backreffing grouping paren</span></li><li>            <span class="q">            [^&gt;&#39;&quot;] *        # 0 or more things that are neither &gt; nor &#39; nor &quot;</span></li><li>                <span class="q">                |           #    or else</span></li><li>            <span class="q">            &quot;.*?&quot;           # a section between double quotes (stingy match)</span></li><li>                <span class="q">                |           #    or else</span></li><li>            <span class="q">            &#39;.*?&#39;           # a section between single quotes (stingy match)</span></li><li>        <span class="q">        ) +                 #   all occurring one or more times</span></li><li>        <span class="q">        &gt;                   # closing angle bracket</span></li><li>    <span class="q">    }{}gsx</span><span class="sc">;</span>                 <span class="c"># replace with nothing, i.e. delete</span></li></ol></pre><p>It's still not quite so clear as prose, but it is very useful for
describing the meaning of each part of the pattern.</p>
</li>
<li><a name="Different-Delimiters"></a><b>Different Delimiters</b>
<p>While we normally think of patterns as being delimited with <code class="inline">/</code>
characters, they can be delimited by almost any character. <a href="perlre.html">perlre</a>
describes this. For example, the <code class="inline"><a class="l_k" href="functions/s.html">s///</a></code> above uses braces as
delimiters. Selecting another delimiter can avoid quoting the
delimiter within the pattern:</p>
<pre class="verbatim"><ol><li>    <span class="q">s/\/usr\/local/\/usr\/share/g</span><span class="sc">;</span>    <span class="c"># bad delimiter choice</span></li><li>    <span class="q">s#/usr/local#/usr/share#g</span><span class="sc">;</span>        <span class="c"># better</span></li></ol></pre><p>Using logically paired delimiters can be even more readable:</p>
<pre class="verbatim"><ol><li>    <span class="q">s{/usr/local/}{/usr/share}g</span><span class="sc">;</span>      <span class="c"># better still</span></li></ol></pre></li>
</ul>
<a name="I'm-having-trouble-matching-over-more-than-one-line.-What's-wrong%3f"></a><h2>I'm having trouble matching over more than one line. What's wrong?
  </h2>
<p>Either you don't have more than one line in the string you're looking
at (probably), or else you aren't using the correct modifier(s) on
your pattern (possibly).</p>
<p>There are many ways to get multiline data into a string. If you want
it to happen automatically while reading input, you'll want to set $/
(probably to '' for paragraphs or <code class="inline"><a class="l_k" href="functions/undef.html">undef</a></code> for the whole file) to
allow you to read more than one line at a time.</p>
<p>Read <a href="perlre.html">perlre</a> to help you decide which of <code class="inline">/s</code> and <code class="inline">/m</code> (or both)
you might want to use: <code class="inline">/s</code> allows dot to include newline, and <code class="inline">/m</code>
allows caret and dollar to match next to a newline, not just at the
end of the string. You do need to make sure that you've actually
got a multiline string in there.</p>
<p>For example, this program detects duplicate words, even when they span
line breaks (but not paragraph ones). For this example, we don't need
<code class="inline">/s</code> because we aren't using dot in a regular expression that we want
to cross line boundaries. Neither do we need <code class="inline">/m</code> because we don't
want caret or dollar to match at any point inside the record next
to newlines. But it's imperative that $/ be set to something other
than the default, or else we won't actually ever have a multiline
record read in.</p>
<pre class="verbatim"><ol><li>    <span class="i">$/</span> = <span class="q">&#39;&#39;</span><span class="sc">;</span>          <span class="c"># read in whole paragraph, not just one line</span></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <span class="q">/\b([\w&#39;-]+)(\s+\g1)+\b/gi</span> <span class="s">)</span> <span class="s">{</span>     <span class="c"># word starts alpha</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Duplicate $1 at paragraph $.\n&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Here's some code that finds sentences that begin with "From " (which would
be mangled by many mailers):</p>
<pre class="verbatim"><ol><li>    <span class="i">$/</span> = <span class="q">&#39;&#39;</span><span class="sc">;</span>          <span class="c"># read in whole paragraph, not just one line</span></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <span class="q">/^From /gm</span> <span class="s">)</span> <span class="s">{</span> <span class="c"># /m makes ^ match next to \n</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;leading from in paragraph $.\n&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Here's code that finds everything between START and END in a paragraph:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/undef.html">undef</a> <span class="i">$/</span><span class="sc">;</span>          <span class="c"># read in whole file, not just one line or paragraph</span></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <span class="q">/START(.*?)END/sgm</span> <span class="s">)</span> <span class="s">{</span> <span class="c"># /s makes . cross line boundaries</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$1\n&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines%3f"></a><h2>How can I pull out lines between two patterns that are themselves on different lines?
</h2>
<p>You can use Perl's somewhat exotic <code class="inline">..</code>
 operator (documented in
<a href="perlop.html">perlop</a>):</p>
<pre class="verbatim"><ol><li>    perl -ne 'print if /START/ .. /END/' file1 file2 ...</li></ol></pre><p>If you wanted text and not lines, you would use</p>
<pre class="verbatim"><ol><li>    perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ...</li></ol></pre><p>But if you want nested occurrences of <code class="inline"><span class="w">START</span></code>
 through <code class="inline">END</code>
, you'll
run up against the problem described in the question in this section
on matching balanced text.</p>
<p>Here's another example of using <code class="inline">..</code>
:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$in_header</span> =   <span class="n">1</span>  .. <span class="q">/^$/</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$in_body</span>   = <span class="q">/^$/</span> .. <a class="l_k" href="functions/eof.html">eof</a><span class="sc">;</span></li><li>    <span class="c"># now choose between them</span></li><li>    <span class="s">}</span> <a class="l_k" href="functions/continue.html">continue</a> <span class="s">{</span></li><li>        <span class="i">$.</span> = <span class="n">0</span> <a class="l_k" href="functions/if.html">if</a> <a class="l_k" href="functions/eof.html">eof</a><span class="sc">;</span>    <span class="c"># fix $.</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-do-I-match-XML%2c-HTML%2c-or-other-nasty%2c-ugly-things-with-a-regex%3f"></a><h2>How do I match XML, HTML, or other nasty, ugly things with a regex?
     
</h2>
<p>Do not use regexes. Use a module and forget about the
regular expressions. The <a href="http://search.cpan.org/perldoc/XML::LibXML">XML::LibXML</a>, <a href="http://search.cpan.org/perldoc/HTML::TokeParser">HTML::TokeParser</a> and
<a href="http://search.cpan.org/perldoc/HTML::TreeBuilder">HTML::TreeBuilder</a> modules are good starts, although each namespace
has other parsing modules specialized for certain tasks and different
ways of doing it. Start at CPAN Search ( <a href="http://metacpan.org/">http://metacpan.org/</a> )
and wonder at all the work people have done for you already! :)</p>
<a name="I-put-a-regular-expression-into-%24%2f-but-it-didn't-work.-What's-wrong%3f"></a><h2>I put a regular expression into $/ but it didn't work. What's wrong?
 
</h2>
<p>$/ has to be a string. You can use these examples if you really need to
do this.</p>
<p>If you have <a href="http://search.cpan.org/perldoc/File::Stream">File::Stream</a>, this is easy.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Stream</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$stream</span> = <span class="w">File::Stream</span><span class="w">-&gt;new</span><span class="s">(</span></li><li>        <span class="i">$filehandle</span><span class="cm">,</span></li><li>        <span class="w">separator</span> <span class="cm">=&gt;</span> <span class="q">qr/\s*,\s*/</span><span class="cm">,</span></li><li>        <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$_\n&quot;</span> <a class="l_k" href="functions/while.html">while</a> <span class="q">&lt;$stream&gt;</span><span class="sc">;</span></li></ol></pre><p>If you don't have File::Stream, you have to do a little more work.</p>
<p>You can use the four-argument form of sysread to continually add to
a buffer. After you add to the buffer, you check if you have a
complete line (using your regular expression).</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/local.html">local</a> <span class="i">$_</span> = <span class="q">&quot;&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <a class="l_k" href="functions/sysread.html">sysread</a> <span class="w">FH</span><span class="cm">,</span> <span class="i">$_</span><span class="cm">,</span> <span class="n">8192</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <span class="q">s/^((?s).*?)your_pattern//</span> <span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/my.html">my</a> <span class="i">$record</span> = <span class="i">$1</span><span class="sc">;</span></li><li>            <span class="c"># do stuff here.</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>You can do the same thing with foreach and a match using the
c flag and the \G anchor, if you do not mind your entire file
being in memory at the end.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/local.html">local</a> <span class="i">$_</span> = <span class="q">&quot;&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <a class="l_k" href="functions/sysread.html">sysread</a> <span class="w">FH</span><span class="cm">,</span> <span class="i">$_</span><span class="cm">,</span> <span class="n">8192</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/foreach.html">foreach</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$record</span> <span class="s">(</span> <span class="q">m/\G((?s).*?)your_pattern/gc</span> <span class="s">)</span> <span class="s">{</span></li><li>            <span class="c"># do stuff here.</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$_</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <a class="l_k" href="functions/pos.html">pos</a> <span class="s">)</span> = <span class="q">&quot;&quot;</span> <a class="l_k" href="functions/if.html">if</a> <a class="l_k" href="functions/pos.html">pos</a><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS%3f"></a><h2>How do I substitute case-insensitively on the LHS while preserving case on the RHS?
 
 </h2>
<p>Here's a lovely Perlish solution by Larry Rosler. It exploits
properties of bitwise xor on ASCII strings.</p>
<pre class="verbatim"><ol><li>    <span class="i">$_</span>= <span class="q">&quot;this is a TEsT case&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$old</span> = <span class="q">&#39;test&#39;</span><span class="sc">;</span></li><li>    <span class="i">$new</span> = <span class="q">&#39;success&#39;</span><span class="sc">;</span></li><li></li><li>    <span class="q">s{(\Q$old\E)}</span></li><li>    <span class="q">    { uc $new | (uc $1 ^ $1) .</span></li><li>        <span class="q">        (uc(substr $1, -1) ^ substr $1, -1) x</span></li><li>        <span class="q">        (length($new) - length $1)</span></li><li>    <span class="q">    }egi</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="sc">;</span></li></ol></pre><p>And here it is as a subroutine, modeled after the above:</p>
<pre class="verbatim"><ol><li><a name="preserve_case"></a>    sub <span class="m">preserve_case</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$old</span><span class="cm">,</span> <span class="i">$new</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$mask</span> = <a class="l_k" href="functions/uc.html">uc</a> <span class="i">$old</span> ^ <span class="i">$old</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/uc.html">uc</a> <span class="i">$new</span> | <span class="i">$mask</span> .</li><li>            <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$mask</span><span class="cm">,</span> <span class="n">-1</span><span class="s">)</span> x <span class="s">(</span><a class="l_k" href="functions/length.html">length</a><span class="s">(</span><span class="i">$new</span><span class="s">)</span> - <a class="l_k" href="functions/length.html">length</a><span class="s">(</span><span class="i">$old</span><span class="s">)</span><span class="s">)</span></li><li>    <span class="s">}</span></li><li></li><li>    <span class="i">$string</span> = <span class="q">&quot;this is a TEsT case&quot;</span><span class="sc">;</span></li><li>    <span class="i">$string</span> =~ <span class="q">s/(test)/preserve_case($1, &quot;success&quot;)/egi</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$string\n&quot;</span><span class="sc">;</span></li></ol></pre><p>This prints:</p>
<pre class="verbatim"><ol><li>    <span class="w">this</span> <span class="w">is</span> <span class="w">a</span> <span class="w">SUcCESS</span> case</li></ol></pre><p>As an alternative, to keep the case of the replacement word if it is
longer than the original, you can use this code, by Jeff Pinyan:</p>
<pre class="verbatim"><ol><li><a name="preserve_case"></a>    sub <span class="m">preserve_case</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$from</span><span class="cm">,</span> <span class="i">$to</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$lf</span><span class="cm">,</span> <span class="i">$lt</span><span class="s">)</span> = <a class="l_k" href="functions/map.html">map</a> <a class="l_k" href="functions/length.html">length</a><span class="cm">,</span> <span class="i">@_</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$lt</span> &lt; <span class="i">$lf</span><span class="s">)</span> <span class="s">{</span> <span class="i">$from</span> = <a class="l_k" href="functions/substr.html">substr</a> <span class="i">$from</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="i">$lt</span> <span class="s">}</span></li><li>        <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span> <span class="i">$from</span> .= <a class="l_k" href="functions/substr.html">substr</a> <span class="i">$to</span><span class="cm">,</span> <span class="i">$lf</span> <span class="s">}</span></li><li></li><li>        <a class="l_k" href="functions/return.html">return</a> <a class="l_k" href="functions/uc.html">uc</a> <span class="i">$to</span> | <span class="s">(</span><span class="i">$from</span> ^ <a class="l_k" href="functions/uc.html">uc</a> <span class="i">$from</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>This changes the sentence to "this is a SUcCess case."</p>
<p>Just to show that C programmers can write C in any programming language,
if you prefer a more C-like solution, the following script makes the
substitution have the same case, letter by letter, as the original.
(It also happens to run about 240% slower than the Perlish solution runs.)
If the substitution has more characters than the string being substituted,
the case of the last character is used for the rest of the substitution.</p>
<pre class="verbatim"><ol><li>    <span class="c"># Original by Nathan Torkington, massaged by Jeffrey Friedl</span></li><li>    <span class="c">#</span></li><li><a name="preserve_case"></a>    sub <span class="m">preserve_case</span></li><li>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$old</span><span class="cm">,</span> <span class="i">$new</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$state</span> = <span class="n">0</span><span class="sc">;</span> <span class="c"># 0 = no change; 1 = lc; 2 = uc</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$i</span><span class="cm">,</span> <span class="i">$oldlen</span><span class="cm">,</span> <span class="i">$newlen</span><span class="cm">,</span> <span class="i">$c</span><span class="s">)</span> = <span class="s">(</span><span class="n">0</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a><span class="s">(</span><span class="i">$old</span><span class="s">)</span><span class="cm">,</span> <a class="l_k" href="functions/length.html">length</a><span class="s">(</span><span class="i">$new</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/my.html">my</a> <span class="i">$len</span> = <span class="i">$oldlen</span> &lt; <span class="i">$newlen</span> ? <span class="i">$oldlen</span> <span class="co">:</span> <span class="i">$newlen</span><span class="sc">;</span></li><li></li><li>        <a class="l_k" href="functions/for.html">for</a> <span class="s">(</span><span class="i">$i</span> = <span class="n">0</span><span class="sc">;</span> <span class="i">$i</span> &lt; <span class="i">$len</span><span class="sc">;</span> <span class="i">$i</span>++<span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$c</span> = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$old</span><span class="cm">,</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="cm">,</span> <span class="i">$c</span> =~ <span class="q">/[\W\d_]/</span><span class="s">)</span> <span class="s">{</span></li><li>                <span class="i">$state</span> = <span class="n">0</span><span class="sc">;</span></li><li>            <span class="s">}</span> <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><a class="l_k" href="functions/lc.html">lc</a> <span class="i">$c</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="i">$c</span><span class="s">)</span> <span class="s">{</span></li><li>                <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span> = <a class="l_k" href="functions/lc.html">lc</a><span class="s">(</span><a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>                <span class="i">$state</span> = <span class="n">1</span><span class="sc">;</span></li><li>            <span class="s">}</span> <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>                <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span> = <a class="l_k" href="functions/uc.html">uc</a><span class="s">(</span><a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$i</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>                <span class="i">$state</span> = <span class="n">2</span><span class="sc">;</span></li><li>            <span class="s">}</span></li><li>        <span class="s">}</span></li><li>        <span class="c"># finish up with any remaining new (for when new is longer than old)</span></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$newlen</span> &gt; <span class="i">$oldlen</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$state</span> == <span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li>                <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$oldlen</span><span class="s">)</span> = <a class="l_k" href="functions/lc.html">lc</a><span class="s">(</span><a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$oldlen</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>            <span class="s">}</span> <a class="l_k" href="functions/elsif.html">elsif</a> <span class="s">(</span><span class="i">$state</span> == <span class="n">2</span><span class="s">)</span> <span class="s">{</span></li><li>                <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$oldlen</span><span class="s">)</span> = <a class="l_k" href="functions/uc.html">uc</a><span class="s">(</span><a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$new</span><span class="cm">,</span> <span class="i">$oldlen</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>            <span class="s">}</span></li><li>        <span class="s">}</span></li><li>        <a class="l_k" href="functions/return.html">return</a> <span class="i">$new</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-can-I-make-%5cw-match-national-character-sets%3f"></a><h2>How can I make <code class="inline">\<span class="w">w</span></code>
 match national character sets?
</h2>
<p>Put <code class="inline"><a class="l_k" href="functions/use.html">use</a> <span class="w">locale</span><span class="sc">;</span></code>
 in your script. The \w character class is taken
from the current locale.</p>
<p>See <a href="perllocale.html">perllocale</a> for details.</p>
<a name="How-can-I-match-a-locale-smart-version-of-%2f%5ba-zA-Z%5d%2f%3f"></a><h2>How can I match a locale-smart version of <code class="inline"><span class="q">/[a-zA-Z]/</span></code>
?
</h2>
<p>You can use the POSIX character class syntax <code class="inline"><span class="q">/[[:alpha:]]/</span></code>

documented in <a href="perlre.html">perlre</a>.</p>
<p>No matter which locale you are in, the alphabetic characters are
the characters in \w without the digits and the underscore.
As a regex, that looks like <code class="inline"><span class="q">/[^\W\d_]/</span></code>
. Its complement,
the non-alphabetics, is then everything in \W along with
the digits and the underscore, or <code class="inline"><span class="q">/[\W\d_]/</span></code>
.</p>
<a name="How-can-I-quote-a-variable-to-use-in-a-regex%3f"></a><h2>How can I quote a variable to use in a regex?
  </h2>
<p>The Perl parser will expand $variable and @variable references in
regular expressions unless the delimiter is a single quote. Remember,
too, that the right-hand side of a <code class="inline"><a class="l_k" href="functions/s.html">s///</a></code> substitution is considered
a double-quoted string (see <a href="perlop.html">perlop</a> for more details). Remember
also that any regex special characters will be acted on unless you
precede the substitution with \Q. Here's an example:</p>
<pre class="verbatim"><ol><li>    <span class="i">$string</span> = <span class="q">&quot;Placido P. Octopus&quot;</span><span class="sc">;</span></li><li>    <span class="i">$regex</span>  = <span class="q">&quot;P.&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$string</span> =~ <span class="q">s/$regex/Polyp/</span><span class="sc">;</span></li><li>    <span class="c"># $string is now &quot;Polypacido P. Octopus&quot;</span></li></ol></pre><p>Because <code class="inline">.</code> is special in regular expressions, and can match any
single character, the regex <code class="inline"><span class="w">P</span>.</code>
 here has matched the &lt;Pl&gt; in the
original string.</p>
<p>To escape the special meaning of <code class="inline">.</code>, we use <code class="inline">\<span class="w">Q</span></code>
:</p>
<pre class="verbatim"><ol><li>    <span class="i">$string</span> = <span class="q">&quot;Placido P. Octopus&quot;</span><span class="sc">;</span></li><li>    <span class="i">$regex</span>  = <span class="q">&quot;P.&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="i">$string</span> =~ <span class="q">s/\Q$regex/Polyp/</span><span class="sc">;</span></li><li>    <span class="c"># $string is now &quot;Placido Polyp Octopus&quot;</span></li></ol></pre><p>The use of <code class="inline">\<span class="w">Q</span></code>
 causes the &lt;.&gt; in the regex to be treated as a
regular character, so that <code class="inline"><span class="w">P</span>.</code>
 matches a <code class="inline"><span class="w">P</span></code>
 followed by a dot.</p>
<a name="What-is-%2fo-really-for%3f"></a><h2>What is <code class="inline">/o</code> really for?
 </h2>
<p>(contributed by brian d foy)</p>
<p>The <code class="inline">/o</code> option for regular expressions (documented in <a href="perlop.html">perlop</a> and
<a href="perlreref.html">perlreref</a>) tells Perl to compile the regular expression only once.
This is only useful when the pattern contains a variable. Perls 5.6
and later handle this automatically if the pattern does not change.</p>
<p>Since the match operator <code class="inline"><a class="l_k" href="functions/m.html">m//</a></code>, the substitution operator <code class="inline"><a class="l_k" href="functions/s.html">s///</a></code>,
and the regular expression quoting operator <code class="inline"><a class="l_k" href="functions/qr.html">qr//</a></code> are double-quotish
constructs, you can interpolate variables into the pattern. See the
answer to "How can I quote a variable to use in a regex?" for more
details.</p>
<p>This example takes a regular expression from the argument list and
prints the lines of input that match it:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$pattern</span> = <a class="l_k" href="functions/shift.html">shift</a> <span class="i">@ARGV</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/if.html">if</a> <span class="q">m/$pattern/</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Versions of Perl prior to 5.6 would recompile the regular expression
for each iteration, even if <code class="inline"><span class="i">$pattern</span></code>
 had not changed. The <code class="inline">/o</code>
would prevent this by telling Perl to compile the pattern the first
time, then reuse that for subsequent iterations:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$pattern</span> = <a class="l_k" href="functions/shift.html">shift</a> <span class="i">@ARGV</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/if.html">if</a> <span class="q">m/$pattern/o</span><span class="sc">;</span> <span class="c"># useful for Perl &lt; 5.6</span></li><li>    <span class="s">}</span></li></ol></pre><p>In versions 5.6 and later, Perl won't recompile the regular expression
if the variable hasn't changed, so you probably don't need the <code class="inline">/o</code>
option. It doesn't hurt, but it doesn't help either. If you want any
version of Perl to compile the regular expression only once even if
the variable changes (thus, only using its initial value), you still
need the <code class="inline">/o</code>.</p>
<p>You can watch Perl's regular expression engine at work to verify for
yourself if Perl is recompiling a regular expression. The <code class="inline"><a class="l_k" href="functions/use.html">use</a> <span class="w">re</span>
<span class="q">'debug'</span></code>
 pragma (comes with Perl 5.005 and later) shows the details.
With Perls before 5.6, you should see <code class="inline"><span class="w">re</span></code>
 reporting that its
compiling the regular expression on each iteration. With Perl 5.6 or
later, you should only see <code class="inline"><span class="w">re</span></code>
 report that for the first iteration.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">re</span> <span class="q">&#39;debug&#39;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <span class="q">&#39;Perl&#39;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/foreach.html">foreach</a> <span class="s">(</span> <span class="q">qw(Perl Java Ruby Python)</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">STDERR</span> <span class="q">&quot;-&quot;</span> x <span class="n">73</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">STDERR</span> <span class="q">&quot;Trying $_...\n&quot;</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">STDERR</span> <span class="q">&quot;\t$_ is good!\n&quot;</span> <a class="l_k" href="functions/if.html">if</a> <span class="q">m/$regex/</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file%3f"></a><h2>How do I use a regular expression to strip C-style comments from a file?</h2>
<p>While this actually can be done, it's much harder than you'd think.
For example, this one-liner</p>
<pre class="verbatim"><ol><li>    perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c</li></ol></pre><p>will work in many but not all cases. You see, it's too simple-minded for
certain kinds of C programs, in particular, those with what appear to be
comments in quoted strings. For that, you'd need something like this,
created by Jeffrey Friedl and later modified by Fred Curtis.</p>
<pre class="verbatim"><ol><li>    <span class="i">$/</span> = <a class="l_k" href="functions/undef.html">undef</a><span class="sc">;</span></li><li>    <span class="i">$_</span> = &lt;&gt;<span class="sc">;</span></li><li>    <span class="q">s#/\*[^*]*\*+([^/*][^*]*\*+)*/|(&quot;(\\.|[^&quot;\\])*&quot;|&#39;(\\.|[^&#39;\\])*&#39;|.[^/&quot;&#39;\\]*)#defined $2 ? $2 : &quot;&quot;#gse</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a><span class="sc">;</span></li></ol></pre><p>This could, of course, be more legibly written with the <code class="inline">/x</code> modifier, adding
whitespace and comments. Here it is expanded, courtesy of Fred Curtis.</p>
<pre class="verbatim"><ol><li>    <span class="q">s{</span></li><li>       <span class="q">       /\*         ##  Start of /* ... */ comment</span></li><li>       <span class="q">       [^*]*\*+    ##  Non-* followed by 1-or-more *&#39;s</span></li><li>       <span class="q">       (</span></li><li>         <span class="q">         [^/*][^*]*\*+</span></li><li>       <span class="q">       )*          ##  0-or-more things which don&#39;t start with /</span></li><li>                   <span class="q">                   ##    but do end with &#39;*&#39;</span></li><li>       <span class="q">       /           ##  End of /* ... */ comment</span></li><li></li><li>     <span class="q">     |         ##     OR  various things which aren&#39;t comments:</span></li><li></li><li>       <span class="q">       (</span></li><li>         <span class="q">         &quot;           ##  Start of &quot; ... &quot; string</span></li><li>         <span class="q">         (</span></li><li>           <span class="q">           \\.           ##  Escaped char</span></li><li>         <span class="q">         |               ##    OR</span></li><li>           <span class="q">           [^&quot;\\]        ##  Non &quot;\</span></li><li>         <span class="q">         )*</span></li><li>         <span class="q">         &quot;           ##  End of &quot; ... &quot; string</span></li><li></li><li>       <span class="q">       |         ##     OR</span></li><li></li><li>         <span class="q">         &#39;           ##  Start of &#39; ... &#39; string</span></li><li>         <span class="q">         (</span></li><li>           <span class="q">           \\.           ##  Escaped char</span></li><li>         <span class="q">         |               ##    OR</span></li><li>           <span class="q">           [^&#39;\\]        ##  Non &#39;\</span></li><li>         <span class="q">         )*</span></li><li>         <span class="q">         &#39;           ##  End of &#39; ... &#39; string</span></li><li></li><li>       <span class="q">       |         ##     OR</span></li><li></li><li>         <span class="q">         .           ##  Anything other char</span></li><li>         <span class="q">         [^/&quot;&#39;\\]*   ##  Chars which doesn&#39;t start a comment, string or escape</span></li><li>       <span class="q">       )</span></li><li>     <span class="q">     }{defined $2 ? $2 : &quot;&quot;}gxse</span><span class="sc">;</span></li></ol></pre><p>A slight modification also removes C++ comments, possibly spanning multiple lines
using a continuation character:</p>
<pre class="verbatim"><ol><li> <span class="q">s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|(&quot;(\\.|[^&quot;\\])*&quot;|&#39;(\\.|[^&#39;\\])*&#39;|.[^/&quot;&#39;\\]*)#defined $3 ? $3 : &quot;&quot;#gse</span><span class="sc">;</span></li></ol></pre><a name="Can-I-use-Perl-regular-expressions-to-match-balanced-text%3f"></a><h2>Can I use Perl regular expressions to match balanced text?
 
  
   </h2>
<p>(contributed by brian d foy)</p>
<p>Your first try should probably be the <a href="Text/Balanced.html">Text::Balanced</a> module, which
is in the Perl standard library since Perl 5.8. It has a variety of
functions to deal with tricky text. The <a href="http://search.cpan.org/perldoc/Regexp::Common">Regexp::Common</a> module can
also help by providing canned patterns you can use.</p>
<p>As of Perl 5.10, you can match balanced text with regular expressions
using recursive patterns. Before Perl 5.10, you had to resort to
various tricks such as using Perl code in <code class="inline"><span class="s">(</span><span class="q">??</span><span class="s">{</span><span class="s">}</span><span class="s">)</span></code>
 sequences.</p>
<p>Here's an example using a recursive regular expression. The goal is to
capture all of the text within angle brackets, including the text in
nested angle brackets. This sample text has two "major" groups: a
group with one level of nesting and a group with two levels of
nesting. There are five total groups in angle brackets:</p>
<pre class="verbatim"><ol><li>    <span class="w">I</span> <span class="w">have</span> <span class="w">some</span> &lt;<span class="w">brackets</span> <span class="w">in</span> <span class="q">&lt;nested brackets&gt;</span> &gt; <a class="l_k" href="functions/and.html">and</a></li><li>    <span class="q">&lt;another group &lt;nested once &lt;nested twice&gt;</span> &gt; &gt;</li><li>    <a class="l_k" href="functions/and.html">and</a> <span class="w">that&#39;s</span> <span class="w">it</span>.</li></ol></pre><p>The regular expression to match the balanced text uses two new (to
Perl 5.10) regular expression features. These are covered in <a href="perlre.html">perlre</a>
and this example is a modified version of one in that documentation.</p>
<p>First, adding the new possessive <code class="inline">+</code>
 to any quantifier finds the
longest match and does not backtrack. That's important since you want
to handle any angle brackets through the recursion, not backtracking.
The group <code class="inline">[^&lt;&gt;]++</code> finds one or more non-angle brackets without
backtracking.</p>
<p>Second, the new <code class="inline">(?PARNO)</code> refers to the sub-pattern in the
particular capture group given by <code class="inline"><span class="w">PARNO</span></code>
. In the following regex,
the first capture group finds (and remembers) the balanced text, and
you need that same pattern within the first buffer to get past the
nested text. That's the recursive part. The <code class="inline">(?1)</code> uses the pattern
in the outer capture group as an independent part of the regex.</p>
<p>Putting it all together, you have:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/local/bin/perl5.10.0</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$string</span> =<span class="h">&lt;&lt;&quot;HERE&quot;</span><span class="sc">;</span></li><li><span class="hh">    I have some &lt;brackets in &lt;nested brackets&gt; &gt; and</span></li><li><span class="hh">    &lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;</span></li><li><span class="hh">    and that&#39;s it.</span></li><li><span class="hh">    HERE</span></li><li></li><li><span class="hh">    my @groups = $string =~ m/</span></li><li><span class="hh">            (                   # start of capture group 1</span></li><li><span class="hh">            &lt;                   # match an opening angle bracket</span></li><li><span class="hh">                (?:</span></li><li><span class="hh">                    [^&lt;&gt;]++     # one or more non angle brackets, non backtracking</span></li><li><span class="hh">                      |</span></li><li><span class="hh">                    (?1)        # found &lt; or &gt;, so recurse to capture group 1</span></li><li><span class="hh">                )*</span></li><li><span class="hh">            &gt;                   # match a closing angle bracket</span></li><li><span class="hh">            )                   # end of capture group 1</span></li><li><span class="hh">            /xg;</span></li><li></li><li><span class="hh">    $&quot; = &quot;\n\t&quot;;</span></li><li><span class="hh">    print &quot;Found:\n\t@groups\n&quot;;</span></li></ol></pre><p>The output shows that Perl found the two major groups:</p>
<pre class="verbatim"><ol><li>    <span class="j">Found:</span></li><li>        <span class="q">&lt;brackets in &lt;nested brackets&gt;</span> &gt;</li><li>        <span class="q">&lt;another group &lt;nested once &lt;nested twice&gt;</span> &gt; &gt;</li></ol></pre><p>With a little extra work, you can get all of the groups in angle
brackets even if they are in other angle brackets too. Each time you
get a balanced match, remove its outer delimiter (that's the one you
just matched so don't match it again) and add it to a queue of strings
to process. Keep doing that until you get no matches:</p>
<pre class="verbatim"><ol><li>    <span class="c">#!/usr/local/bin/perl5.10.0</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@queue</span> =<span class="h">&lt;&lt;&quot;HERE&quot;</span><span class="sc">;</span></li><li><span class="hh">    I have some &lt;brackets in &lt;nested brackets&gt; &gt; and</span></li><li><span class="hh">    &lt;another group &lt;nested once &lt;nested twice&gt; &gt; &gt;</span></li><li><span class="hh">    and that&#39;s it.</span></li><li><span class="hh">    HERE</span></li><li></li><li><span class="hh">    my $regex = qr/</span></li><li><span class="hh">            (                   # start of bracket 1</span></li><li><span class="hh">            &lt;                   # match an opening angle bracket</span></li><li><span class="hh">                (?:</span></li><li><span class="hh">                    [^&lt;&gt;]++     # one or more non angle brackets, non backtracking</span></li><li><span class="hh">                      |</span></li><li><span class="hh">                    (?1)        # recurse to bracket 1</span></li><li><span class="hh">                )*</span></li><li><span class="hh">            &gt;                   # match a closing angle bracket</span></li><li><span class="hh">            )                   # end of bracket 1</span></li><li><span class="hh">            /x;</span></li><li></li><li><span class="hh">    $&quot; = &quot;\n\t&quot;;</span></li><li></li><li><span class="hh">    while( @queue ) {</span></li><li><span class="hh">        my $string = shift @queue;</span></li><li></li><li><span class="hh">        my @groups = $string =~ m/$regex/g;</span></li><li><span class="hh">        print &quot;Found:\n\t@groups\n\n&quot; if @groups;</span></li><li></li><li><span class="hh">        unshift @queue, map { s/^&lt;//; s/&gt;$//; $_ } @groups;</span></li><li><span class="hh">    }</span></li></ol></pre><p>The output shows all of the groups. The outermost matches show up
first and the nested matches show up later:</p>
<pre class="verbatim"><ol><li>    <span class="j">Found:</span></li><li>        <span class="q">&lt;brackets in &lt;nested brackets&gt;</span> &gt;</li><li>        <span class="q">&lt;another group &lt;nested once &lt;nested twice&gt;</span> &gt; &gt;</li><li></li><li>    <span class="w">Found</span><span class="co">:</span></li><li>        <span class="q">&lt;nested brackets&gt;</span></li><li></li><li>    <span class="w">Found</span><span class="co">:</span></li><li>        <span class="q">&lt;nested once &lt;nested twice&gt;</span> &gt;</li><li></li><li>    <span class="w">Found</span><span class="co">:</span></li><li>        <span class="q">&lt;nested twice&gt;</span></li></ol></pre><a name="What-does-it-mean-that-regexes-are-greedy%3f-How-can-I-get-around-it%3f"></a><h2>What does it mean that regexes are greedy? How can I get around it?
 </h2>
<p>Most people mean that greedy regexes match as much as they can.
Technically speaking, it's actually the quantifiers (<code class="inline">?</code>, <code class="inline"><span class="i">*</span></code>
, <code class="inline">+</code>
,
<code class="inline"><span class="s">{</span><span class="s">}</span></code>
) that are greedy rather than the whole pattern; Perl prefers local
greed and immediate gratification to overall greed. To get non-greedy
versions of the same quantifiers, use (<code class="inline"><span class="q">??</span></code>
, <code class="inline"><span class="i">*?</span></code>
, <code class="inline">+?</code>, <code class="inline">{}?</code>).</p>
<p>An example:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$s1</span> = <a class="l_k" href="functions/my.html">my</a> <span class="i">$s2</span> = <span class="q">&quot;I am very very cold&quot;</span><span class="sc">;</span></li><li>    <span class="i">$s1</span> =~ <span class="q">s/ve.*y //</span><span class="sc">;</span>      <span class="c"># I am cold</span></li><li>    <span class="i">$s2</span> =~ <span class="q">s/ve.*?y //</span><span class="sc">;</span>     <span class="c"># I am very cold</span></li></ol></pre><p>Notice how the second substitution stopped matching as soon as it
encountered "y ". The <code class="inline"><span class="i">*?</span></code>
 quantifier effectively tells the regular
expression engine to find a match as quickly as possible and pass
control on to whatever is next in line, as you would if you were
playing hot potato.</p>
<a name="How-do-I-process-each-word-on-each-line%3f"></a><h2>How do I process each word on each line?
</h2>
<p>Use the split function:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/foreach.html">foreach</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$word</span> <span class="s">(</span> <a class="l_k" href="functions/split.html">split</a> <span class="s">)</span> <span class="s">{</span></li><li>            <span class="c"># do something with $word here</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Note that this isn't really a word in the English sense; it's just
chunks of consecutive non-whitespace characters.</p>
<p>To work with only alphanumeric sequences (including underscores), you
might consider</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/foreach.html">foreach</a> <span class="i">$word</span> <span class="s">(</span><span class="q">m/(\w+)/g</span><span class="s">)</span> <span class="s">{</span></li><li>            <span class="c"># do something with $word here</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-can-I-print-out-a-word-frequency-or-line-frequency-summary%3f"></a><h2>How can I print out a word-frequency or line-frequency summary?</h2>
<p>To do this, you have to parse out each word in the input stream. We'll
pretend that by word you mean chunk of alphabetics, hyphens, or
apostrophes, rather than the non-whitespace chunk idea of a word given
in the previous question:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">%seen</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <span class="q">/(\b[^\W_\d][\w&#39;-]+\b)/g</span> <span class="s">)</span> <span class="s">{</span>   <span class="c"># misses &quot;`sheep&#39;&quot;</span></li><li>            <span class="i">$seen</span>{<span class="i">$1</span>}++<span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$word</span><span class="cm">,</span> <span class="i">$count</span><span class="s">)</span> = <a class="l_k" href="functions/each.html">each</a> <span class="i">%seen</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$count $word\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>If you wanted to do the same thing for lines, you wouldn't need a
regular expression:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">%seen</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <span class="i">$seen</span>{<span class="i">$_</span>}++<span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$line</span><span class="cm">,</span> <span class="i">$count</span><span class="s">)</span> = <a class="l_k" href="functions/each.html">each</a> <span class="i">%seen</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$count $line&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>If you want these output in a sorted order, see <a href="perlfaq4.html">perlfaq4</a>: "How do I
sort a hash (optionally by value instead of key)?".</p>
<a name="How-can-I-do-approximate-matching%3f"></a><h2>How can I do approximate matching?
 </h2>
<p>See the module <a href="http://search.cpan.org/perldoc/String::Approx">String::Approx</a> available from CPAN.</p>
<a name="How-do-I-efficiently-match-many-regular-expressions-at-once%3f"></a><h2>How do I efficiently match many regular expressions at once?
 
</h2>
<p>(contributed by brian d foy)</p>
<p>If you have Perl 5.10 or later, this is almost trivial. You just smart
match against an array of regular expression objects:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@patterns</span> = <span class="s">(</span> <span class="q">qr/Fr.d/</span><span class="cm">,</span> <span class="q">qr/B.rn.y/</span><span class="cm">,</span> <span class="q">qr/W.lm./</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="i">$string</span> ~~ <span class="i">@patterns</span> <span class="s">)</span> <span class="s">{</span></li><li>        ...</li><li>    <span class="s">}</span><span class="sc">;</span></li></ol></pre><p>The smart match stops when it finds a match, so it doesn't have to try
every expression.</p>
<p>Earlier than Perl 5.10, you have a bit of work to do. You want to
avoid compiling a regular expression every time you want to match it.
In this example, perl must recompile the regular expression for every
iteration of the <code class="inline">foreach</code>
 loop since it has no way to know what
<code class="inline"><span class="i">$pattern</span></code>
 will be:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@patterns</span> = <span class="q">qw( foo bar baz )</span><span class="sc">;</span></li><li></li><li>    <span class="j">LINE:</span> <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <span class="q">&lt;DATA&gt;</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/foreach.html">foreach</a> <span class="i">$pattern</span> <span class="s">(</span> <span class="i">@patterns</span> <span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="q">/\b$pattern\b/i</span> <span class="s">)</span> <span class="s">{</span></li><li>                <a class="l_k" href="functions/print.html">print</a><span class="sc">;</span></li><li>                <a class="l_k" href="functions/next.html">next</a> <span class="j">LINE</span><span class="sc">;</span></li><li>            <span class="s">}</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>The <code class="inline"><a class="l_k" href="functions/qr.html">qr//</a></code> operator showed up in perl 5.005. It compiles a regular
expression, but doesn't apply it. When you use the pre-compiled
version of the regex, perl does less work. In this example, I inserted
a <code class="inline"><a class="l_k" href="functions/map.html">map</a></code> to turn each pattern into its pre-compiled form. The rest of
the script is the same, but faster:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@patterns</span> = <a class="l_k" href="functions/map.html">map</a> <span class="s">{</span> <span class="q">qr/\b$_\b/i</span> <span class="s">}</span> <span class="q">qw( foo bar baz )</span><span class="sc">;</span></li><li></li><li>    <span class="j">LINE:</span> <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/foreach.html">foreach</a> <span class="i">$pattern</span> <span class="s">(</span> <span class="i">@patterns</span> <span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="q">/$pattern/</span> <span class="s">)</span> <span class="s">{</span></li><li>                <a class="l_k" href="functions/print.html">print</a><span class="sc">;</span></li><li>                <a class="l_k" href="functions/next.html">next</a> <span class="j">LINE</span><span class="sc">;</span></li><li>            <span class="s">}</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>In some cases, you may be able to make several patterns into a single
regular expression. Beware of situations that require backtracking
though.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <a class="l_k" href="functions/join.html">join</a> <span class="q">&#39;|&#39;</span><span class="cm">,</span> <span class="q">qw( foo bar baz )</span><span class="sc">;</span></li><li></li><li>    <span class="j">LINE:</span> <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> &lt;&gt; <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/if.html">if</a> <span class="q">/\b(?:$regex)\b/i</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>For more details on regular expression efficiency, see <i>Mastering
Regular Expressions</i> by Jeffrey Friedl. He explains how the regular
expressions engine works and why some patterns are surprisingly
inefficient. Once you understand how perl applies regular expressions,
you can tune them for individual situations.</p>
<a name="Why-don't-word-boundary-searches-with-%5cb-work-for-me%3f"></a><h2>Why don't word-boundary searches with <code class="inline">\<span class="w">b</span></code>
 work for me?
</h2>
<p>(contributed by brian d foy)</p>
<p>Ensure that you know what \b really does: it's the boundary between a
word character, \w, and something that isn't a word character. That
thing that isn't a word character might be \W, but it can also be the
start or end of the string.</p>
<p>It's not (not!) the boundary between whitespace and non-whitespace,
and it's not the stuff between words we use to create sentences.</p>
<p>In regex speak, a word boundary (\b) is a "zero width assertion",
meaning that it doesn't represent a character in the string, but a
condition at a certain position.</p>
<p>For the regular expression, /\bPerl\b/, there has to be a word
boundary before the "P" and after the "l". As long as something other
than a word character precedes the "P" and succeeds the "l", the
pattern will match. These strings match /\bPerl\b/.</p>
<pre class="verbatim"><ol><li>    <span class="q">&quot;Perl&quot;</span>    <span class="c"># no word char before P or after l</span></li><li>    <span class="q">&quot;Perl &quot;</span>   <span class="c"># same as previous (space is not a word char)</span></li><li>    <span class="q">&quot;&#39;Perl&#39;&quot;</span>  <span class="c"># the &#39; char is not a word char</span></li><li>    <span class="q">&quot;Perl&#39;s&quot;</span>  <span class="c"># no word char before P, non-word char after &quot;l&quot;</span></li></ol></pre><p>These strings do not match /\bPerl\b/.</p>
<pre class="verbatim"><ol><li>    <span class="q">&quot;Perl_&quot;</span>   <span class="c"># _ is a word char!</span></li><li>    <span class="q">&quot;Perler&quot;</span>  <span class="c"># no word char before P, but one after l</span></li></ol></pre><p>You don't have to use \b to match words though. You can look for
non-word characters surrounded by word characters. These strings
match the pattern /\b'\b/.</p>
<pre class="verbatim"><ol><li>    <span class="q">&quot;don&#39;t&quot;</span>   <span class="c"># the &#39; char is surrounded by &quot;n&quot; and &quot;t&quot;</span></li><li>    <span class="q">&quot;qep&#39;a&#39;&quot;</span>  <span class="c"># the &#39; char is surrounded by &quot;p&quot; and &quot;a&quot;</span></li></ol></pre><p>These strings do not match /\b'\b/.</p>
<pre class="verbatim"><ol><li>    <span class="q">&quot;foo&#39;&quot;</span>    <span class="c"># there is no word char after non-word &#39;</span></li></ol></pre><p>You can also use the complement of \b, \B, to specify that there
should not be a word boundary.</p>
<p>In the pattern /\Bam\B/, there must be a word character before the "a"
and after the "m". These patterns match /\Bam\B/:</p>
<pre class="verbatim"><ol><li>    <span class="q">&quot;llama&quot;</span>   <span class="c"># &quot;am&quot; surrounded by word chars</span></li><li>    <span class="q">&quot;Samuel&quot;</span>  <span class="c"># same</span></li></ol></pre><p>These strings do not match /\Bam\B/</p>
<pre class="verbatim"><ol><li>    <span class="q">&quot;Sam&quot;</span>      <span class="c"># no word boundary before &quot;a&quot;, but one after &quot;m&quot;</span></li><li>    <span class="q">&quot;I am Sam&quot;</span> <span class="c"># &quot;am&quot; surrounded by non-word chars</span></li></ol></pre><a name="Why-does-using-%24%26%2c-%24%60%2c-or-%24'-slow-my-program-down%3f"></a><h2>Why does using $&amp;, $`, or $' slow my program down?
     </h2>
<p>(contributed by Anno Siegel)</p>
<p>Once Perl sees that you need one of these variables anywhere in the
program, it provides them on each and every pattern match. That means
that on every pattern match the entire string will be copied, part of it
to $`, part to $&amp;, and part to $'. Thus the penalty is most severe with
long strings and patterns that match often. Avoid $&amp;, $', and $` if you
can, but if you can't, once you've used them at all, use them at will
because you've already paid the price. Remember that some algorithms
really appreciate them. As of the 5.005 release, the $&amp; variable is no
longer "expensive" the way the other two are.</p>
<p>Since Perl 5.6.1 the special variables @- and @+ can functionally replace
$`, $&amp; and $'. These arrays contain pointers to the beginning and end
of each match (see perlvar for the full story), so they give you
essentially the same information, but without the risk of excessive
string copying.</p>
<p>Perl 5.10 added three specials, <code class="inline"><span class="i">$</span>{<span class="w">^MATCH</span>}</code>
, <code class="inline"><span class="i">$</span>{<span class="w">^PREMATCH</span>}</code>
, and
<code class="inline"><span class="i">$</span>{<span class="w">^POSTMATCH</span>}</code>
 to do the same job but without the global performance
penalty. Perl 5.10 only sets these variables if you compile or execute the
regular expression with the <code class="inline">/p</code> modifier.</p>
<a name="What-good-is-%5cG-in-a-regular-expression%3f"></a><h2>What good is <code class="inline">\<span class="w">G</span></code>
 in a regular expression?
</h2>
<p>You use the <code class="inline">\<span class="w">G</span></code>
 anchor to start the next match on the same
string where the last match left off. The regular
expression engine cannot skip over any characters to find
the next match with this anchor, so <code class="inline">\<span class="w">G</span></code>
 is similar to the
beginning of string anchor, <code class="inline">^</code>. The <code class="inline">\<span class="w">G</span></code>
 anchor is typically
used with the <code class="inline"><span class="w">g</span></code>
 flag. It uses the value of <code class="inline"><a class="l_k" href="functions/pos.html">pos()</a></code>
as the position to start the next match. As the match
operator makes successive matches, it updates <code class="inline"><a class="l_k" href="functions/pos.html">pos()</a></code> with the
position of the next character past the last match (or the
first character of the next match, depending on how you like
to look at it). Each string has its own <code class="inline"><a class="l_k" href="functions/pos.html">pos()</a></code> value.</p>
<p>Suppose you want to match all of consecutive pairs of digits
in a string like "1122a44" and stop matching when you
encounter non-digits. You want to match <code class="inline"><span class="n">11</span></code>
 and <code class="inline"><span class="n">22</span></code>
 but
the letter &lt;a&gt; shows up between <code class="inline"><span class="n">22</span></code>
 and <code class="inline"><span class="n">44</span></code>
 and you want
to stop at <code class="inline"><span class="w">a</span></code>
. Simply matching pairs of digits skips over
the <code class="inline"><span class="w">a</span></code>
 and still matches <code class="inline"><span class="n">44</span></code>
.</p>
<pre class="verbatim"><ol><li>    <span class="i">$_</span> = <span class="q">&quot;1122a44&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@pairs</span> = <span class="q">m/(\d\d)/g</span><span class="sc">;</span>   <span class="c"># qw( 11 22 44 )</span></li></ol></pre><p>If you use the <code class="inline">\<span class="w">G</span></code>
 anchor, you force the match after <code class="inline"><span class="n">22</span></code>
 to
start with the <code class="inline"><span class="w">a</span></code>
. The regular expression cannot match
there since it does not find a digit, so the next match
fails and the match operator returns the pairs it already
found.</p>
<pre class="verbatim"><ol><li>    <span class="i">$_</span> = <span class="q">&quot;1122a44&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@pairs</span> = <span class="q">m/\G(\d\d)/g</span><span class="sc">;</span> <span class="c"># qw( 11 22 )</span></li></ol></pre><p>You can also use the <code class="inline">\<span class="w">G</span></code>
 anchor in scalar context. You
still need the <code class="inline"><span class="w">g</span></code>
 flag.</p>
<pre class="verbatim"><ol><li>    <span class="i">$_</span> = <span class="q">&quot;1122a44&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <span class="q">m/\G(\d\d)/g</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Found $1\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>After the match fails at the letter <code class="inline"><span class="w">a</span></code>
, perl resets <code class="inline"><a class="l_k" href="functions/pos.html">pos()</a></code>
and the next match on the same string starts at the beginning.</p>
<pre class="verbatim"><ol><li>    <span class="i">$_</span> = <span class="q">&quot;1122a44&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <span class="q">m/\G(\d\d)/g</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Found $1\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Found $1 after while&quot;</span> <a class="l_k" href="functions/if.html">if</a> <span class="q">m/(\d\d)/g</span><span class="sc">;</span> <span class="c"># finds &quot;11&quot;</span></li></ol></pre><p>You can disable <code class="inline"><a class="l_k" href="functions/pos.html">pos()</a></code> resets on fail with the <code class="inline"><span class="w">c</span></code>
 flag, documented
in <a href="perlop.html">perlop</a> and <a href="perlreref.html">perlreref</a>. Subsequent matches start where the last
successful match ended (the value of <code class="inline"><a class="l_k" href="functions/pos.html">pos()</a></code>) even if a match on the
same string has failed in the meantime. In this case, the match after
the <code class="inline">while<span class="s">(</span><span class="s">)</span></code>
 loop starts at the <code class="inline"><span class="w">a</span></code>
 (where the last match stopped),
and since it does not use any anchor it can skip over the <code class="inline"><span class="w">a</span></code>
 to find
<code class="inline"><span class="n">44</span></code>
.</p>
<pre class="verbatim"><ol><li>    <span class="i">$_</span> = <span class="q">&quot;1122a44&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a><span class="s">(</span> <span class="q">m/\G(\d\d)/gc</span> <span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Found $1\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Found $1 after while&quot;</span> <a class="l_k" href="functions/if.html">if</a> <span class="q">m/(\d\d)/g</span><span class="sc">;</span> <span class="c"># finds &quot;44&quot;</span></li></ol></pre><p>Typically you use the <code class="inline">\<span class="w">G</span></code>
 anchor with the <code class="inline"><span class="w">c</span></code>
 flag
when you want to try a different match if one fails,
such as in a tokenizer. Jeffrey Friedl offers this example
which works in 5.004 or later.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span>&lt;&gt;<span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/chomp.html">chomp</a><span class="sc">;</span></li><li>        <span class="j">PARSER:</span> <span class="s">{</span></li><li>            <span class="q">m/ \G( \d+\b    )/gcx</span>   &amp;&amp; <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;number: $1\n&quot;</span><span class="sc">;</span>  <a class="l_k" href="functions/redo.html">redo</a><span class="sc">;</span> <span class="s">}</span><span class="sc">;</span></li><li>            <span class="q">m/ \G( \w+      )/gcx</span>   &amp;&amp; <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;word:   $1\n&quot;</span><span class="sc">;</span>  <a class="l_k" href="functions/redo.html">redo</a><span class="sc">;</span> <span class="s">}</span><span class="sc">;</span></li><li>            <span class="q">m/ \G( \s+      )/gcx</span>   &amp;&amp; <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;space:  $1\n&quot;</span><span class="sc">;</span>  <a class="l_k" href="functions/redo.html">redo</a><span class="sc">;</span> <span class="s">}</span><span class="sc">;</span></li><li>            <span class="q">m/ \G( [^\w\d]+ )/gcx</span>   &amp;&amp; <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;other:  $1\n&quot;</span><span class="sc">;</span>  <a class="l_k" href="functions/redo.html">redo</a><span class="sc">;</span> <span class="s">}</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>For each line, the <code class="inline"><span class="w">PARSER</span></code>
 loop first tries to match a series
of digits followed by a word boundary. This match has to
start at the place the last match left off (or the beginning
of the string on the first match). Since <code class="inline"><span class="q">m/ \G( \d+\b</span>
<span class="q">)/gcx</span></code>
 uses the <code class="inline"><span class="w">c</span></code>
 flag, if the string does not match that
regular expression, perl does not reset pos() and the next
match starts at the same position to try a different
pattern.</p>
<a name="Are-Perl-regexes-DFAs-or-NFAs%3f-Are-they-POSIX-compliant%3f"></a><h2>Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
  </h2>
<p>While it's true that Perl's regular expressions resemble the DFAs
(deterministic finite automata) of the egrep(1) program, they are in
fact implemented as NFAs (non-deterministic finite automata) to allow
backtracking and backreferencing. And they aren't POSIX-style either,
because those guarantee worst-case behavior for all cases. (It seems
that some people prefer guarantees of consistency, even when what's
guaranteed is slowness.) See the book "Mastering Regular Expressions"
(from O'Reilly) by Jeffrey Friedl for all the details you could ever
hope to know on these matters (a full citation appears in
<a href="perlfaq2.html">perlfaq2</a>).</p>
<a name="What's-wrong-with-using-grep-in-a-void-context%3f"></a><h2>What's wrong with using grep in a void context?
</h2>
<p>The problem is that grep builds a return list, regardless of the context.
This means you're making Perl go to the trouble of building a list that
you then just throw away. If the list is large, you waste both time and space.
If your intent is to iterate over the list, then use a for loop for this
purpose.</p>
<p>In perls older than 5.8.1, map suffers from this problem as well.
But since 5.8.1, this has been fixed, and map is context aware - in void
context, no lists are constructed.</p>
<a name="How-can-I-match-strings-with-multibyte-characters%3f"></a><h2>How can I match strings with multibyte characters?
 
  </h2>
<p>Starting from Perl 5.6 Perl has had some level of multibyte character
support. Perl 5.8 or later is recommended. Supported multibyte
character repertoires include Unicode, and legacy encodings
through the Encode module. See <a href="perluniintro.html">perluniintro</a>, <a href="perlunicode.html">perlunicode</a>,
and <a href="Encode.html">Encode</a>.</p>
<p>If you are stuck with older Perls, you can do Unicode with the
<a href="http://search.cpan.org/perldoc/Unicode::String">Unicode::String</a> module, and character conversions using the
<a href="http://search.cpan.org/perldoc/Unicode::Map8">Unicode::Map8</a> and <a href="http://search.cpan.org/perldoc/Unicode::Map">Unicode::Map</a> modules. If you are using
Japanese encodings, you might try using the jperl 5.005_03.</p>
<p>Finally, the following set of approaches was offered by Jeffrey
Friedl, whose article in issue #5 of The Perl Journal talks about
this very matter.</p>
<p>Let's suppose you have some weird Martian encoding where pairs of
ASCII uppercase letters encode single Martian letters (i.e. the two
bytes "CV" make a single Martian letter, as do the two bytes "SG",
"VS", "XX", etc.). Other bytes represent single characters, just like
ASCII.</p>
<p>So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the
nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'.</p>
<p>Now, say you want to search for the single character <code class="inline"><span class="q">/GX/</span></code>
. Perl
doesn't know about Martian, so it'll find the two bytes "GX" in the "I
am CVSGXX!" string, even though that character isn't there: it just
looks like it is because "SG" is next to "XX", but there's no real
"GX". This is a big problem.</p>
<p>Here are a few ways, all painful, to deal with it:</p>
<pre class="verbatim"><ol><li>    <span class="c"># Make sure adjacent &quot;martian&quot; bytes are no longer adjacent.</span></li><li>    <span class="i">$martian</span> =~ <span class="q">s/([A-Z][A-Z])/ $1 /g</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;found GX!\n&quot;</span> <a class="l_k" href="functions/if.html">if</a> <span class="i">$martian</span> =~ <span class="q">/GX/</span><span class="sc">;</span></li></ol></pre><p>Or like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@chars</span> = <span class="i">$martian</span> =~ <span class="q">m/([A-Z][A-Z]|[^A-Z])/g</span><span class="sc">;</span></li><li>    <span class="c"># above is conceptually similar to:     my @chars = $text =~ m/(.)/g;</span></li><li>    <span class="c">#</span></li><li>    <a class="l_k" href="functions/foreach.html">foreach</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$char</span> <span class="s">(</span><span class="i">@chars</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;found GX!\n&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/last.html">last</a> <a class="l_k" href="functions/if.html">if</a> <span class="i">$char</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="q">&#39;GX&#39;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>Or like this:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="i">$martian</span> =~ <span class="q">m/\G([A-Z][A-Z]|.)/gs</span><span class="s">)</span> <span class="s">{</span>  <span class="c"># \G probably unneeded</span></li><li>        <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="i">$1</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="q">&#39;GX&#39;</span><span class="s">)</span> <span class="s">{</span></li><li>            <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;found GX!\n&quot;</span><span class="sc">;</span></li><li>            <a class="l_k" href="functions/last.html">last</a><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>Here's another, slightly less painful, way to do it from Benjamin
Goldberg, who uses a zero-width negative look-behind assertion.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;found GX!\n&quot;</span> <a class="l_k" href="functions/if.html">if</a>    <span class="i">$martian</span> =~ <span class="q">m/</span></li><li>        <span class="q">        (?&lt;![A-Z])</span></li><li>        <span class="q">        (?:[A-Z][A-Z])*?</span></li><li>        <span class="q">        GX</span></li><li>        <span class="q">        /x</span><span class="sc">;</span></li></ol></pre><p>This succeeds if the "martian" character GX is in the string, and fails
otherwise. If you don't like using (?&lt;!), a zero-width negative
look-behind assertion, you can replace (?&lt;![A-Z]) with (?:^|[^A-Z]).</p>
<p>It does have the drawback of putting the wrong thing in $-[0] and $+[0],
but this usually can be worked around.</p>
<a name="How-do-I-match-a-regular-expression-that's-in-a-variable%3f"></a><h2>How do I match a regular expression that's in a variable?
    
 </h2>
<p>(contributed by brian d foy)</p>
<p>We don't have to hard-code patterns into the match operator (or
anything else that works with regular expressions). We can put the
pattern in a variable for later use.</p>
<p>The match operator is a double quote context, so you can interpolate
your variable just like a double quoted string. In this case, you
read the regular expression as user input and store it in <code class="inline"><span class="i">$regex</span></code>
.
Once you have the pattern in <code class="inline"><span class="i">$regex</span></code>
, you use that variable in the
match operator.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <span class="q">&lt;STDIN&gt;</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="i">$string</span> =~ <span class="q">m/$regex/</span> <span class="s">)</span> <span class="s">{</span> ... <span class="s">}</span></li></ol></pre><p>Any regular expression special characters in <code class="inline"><span class="i">$regex</span></code>
 are still
special, and the pattern still has to be valid or Perl will complain.
For instance, in this pattern there is an unpaired parenthesis.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <span class="q">&quot;Unmatched ( paren&quot;</span><span class="sc">;</span></li><li></li><li>    <span class="q">&quot;Two parens to bind them all&quot;</span> =~ <span class="q">m/$regex/</span><span class="sc">;</span></li></ol></pre><p>When Perl compiles the regular expression, it treats the parenthesis
as the start of a memory match. When it doesn't find the closing
parenthesis, it complains:</p>
<pre class="verbatim"><ol><li>    <span class="w">Unmatched</span> <span class="s">(</span> <span class="w">in</span> <span class="w">regex</span><span class="sc">;</span> <span class="w">marked</span> <span class="w">by</span> &lt;-- <span class="w">HERE</span> <span class="w">in</span> <span class="q">m/Unmatched ( &lt;-- HERE  paren/</span> <span class="w">at</span> <span class="w">script</span> <span class="w">line</span> <span class="n">3.</span></li></ol></pre><p>You can get around this in several ways depending on our situation.
First, if you don't want any of the characters in the string to be
special, you can escape them with <code class="inline"><a class="l_k" href="functions/quotemeta.html">quotemeta</a></code> before you use the string.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <span class="q">&lt;STDIN&gt;</span> <span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$regex</span> = <a class="l_k" href="functions/quotemeta.html">quotemeta</a><span class="s">(</span> <span class="i">$regex</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="i">$string</span> =~ <span class="q">m/$regex/</span> <span class="s">)</span> <span class="s">{</span> ... <span class="s">}</span></li></ol></pre><p>You can also do this directly in the match operator using the <code class="inline">\<span class="w">Q</span></code>

and <code class="inline">\<span class="w">E</span></code>
 sequences. The <code class="inline">\<span class="w">Q</span></code>
 tells Perl where to start escaping
special characters, and the <code class="inline">\<span class="w">E</span></code>
 tells it where to stop (see <a href="perlop.html">perlop</a>
for more details).</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <span class="q">&lt;STDIN&gt;</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="i">$string</span> =~ <span class="q">m/\Q$regex\E/</span> <span class="s">)</span> <span class="s">{</span> ... <span class="s">}</span></li></ol></pre><p>Alternately, you can use <code class="inline"><a class="l_k" href="functions/qr.html">qr//</a></code>, the regular expression quote operator (see
<a href="perlop.html">perlop</a> for more details). It quotes and perhaps compiles the pattern,
and you can apply regular expression flags to the pattern.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$input</span> = <span class="q">&lt;STDIN&gt;</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <span class="q">qr/$input/is</span><span class="sc">;</span></li><li></li><li>    <span class="i">$string</span> =~ <span class="q">m/$regex/</span>  <span class="c"># same as m/$input/is;</span></li></ol></pre><p>You might also want to trap any errors by wrapping an <code class="inline"><a class="l_k" href="functions/eval.html">eval</a></code> block
around the whole thing.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chomp.html">chomp</a><span class="s">(</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$input</span> = <span class="q">&lt;STDIN&gt;</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span></li><li>        <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <span class="i">$string</span> =~ <span class="q">m/\Q$input\E/</span> <span class="s">)</span> <span class="s">{</span> ... <span class="s">}</span></li><li>    <span class="s">}</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/warn.html">warn</a> <span class="i">$@</span> <a class="l_k" href="functions/if.html">if</a> <span class="i">$@</span><span class="sc">;</span></li></ol></pre><p>Or...</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$regex</span> = <a class="l_k" href="functions/eval.html">eval</a> <span class="s">{</span> <span class="q">qr/$input/is</span> <span class="s">}</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/if.html">if</a><span class="s">(</span> <a class="l_k" href="functions/defined.html">defined</a> <span class="i">$regex</span> <span class="s">)</span> <span class="s">{</span></li><li>        <span class="i">$string</span> =~ <span class="q">m/$regex/</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li>    <a class="l_k" href="functions/else.html">else</a> <span class="s">{</span></li><li>        <a class="l_k" href="functions/warn.html">warn</a> <span class="i">$@</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><a name="AUTHOR-AND-COPYRIGHT"></a><h1>AUTHOR AND COPYRIGHT</h1>
<p>Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and
other authors as noted. All rights reserved.</p>
<p>This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.</p>
<p>Irrespective of its distribution, all code examples in this file
are hereby placed into the public domain. You are permitted and
encouraged to use this code in your own programs for fun
or for profit as you see fit. A simple comment in the code giving
credit would be courteous but is not required.</p>




  <div id="page_index" class="hud_container">
    <div id="page_index_header" class="hud_header">
      <div id="page_index_close" class="hud_close"><a href="#" onClick="pageIndex.hide();return false;"></a></div>
      <div id="page_index_title" class="hud_title"><span class="hud_span_top">Page index</span></div>
      <div id="page_index_topright" class="hud_topright"></div>
    </div>
    <div id="page_index_content" class="hud_content">
      <ul><li><a href="#NAME">NAME</a><li><a href="#VERSION">VERSION</a><li><a href="#DESCRIPTION">DESCRIPTION</a><ul><li><a href="#How-can-I-hope-to-use-regular-expressions-without-creating-illegible-and-unmaintainable-code%3f">How can I hope to use regular expressions without creating illegible and unmaintainable code?
 
 </a><li><a href="#I'm-having-trouble-matching-over-more-than-one-line.-What's-wrong%3f">I'm having trouble matching over more than one line. What's wrong?
  </a><li><a href="#How-can-I-pull-out-lines-between-two-patterns-that-are-themselves-on-different-lines%3f">How can I pull out lines between two patterns that are themselves on different lines?
</a><li><a href="#How-do-I-match-XML%2c-HTML%2c-or-other-nasty%2c-ugly-things-with-a-regex%3f">How do I match XML, HTML, or other nasty, ugly things with a regex?
     
</a><li><a href="#I-put-a-regular-expression-into-%24%2f-but-it-didn't-work.-What's-wrong%3f">I put a regular expression into $/ but it didn't work. What's wrong?
 
</a><li><a href="#How-do-I-substitute-case-insensitively-on-the-LHS-while-preserving-case-on-the-RHS%3f">How do I substitute case-insensitively on the LHS while preserving case on the RHS?
 
 </a><li><a href="#How-can-I-make-%5cw-match-national-character-sets%3f">How can I make \w match national character sets?
</a><li><a href="#How-can-I-match-a-locale-smart-version-of-%2f%5ba-zA-Z%5d%2f%3f">How can I match a locale-smart version of /[a-zA-Z]/?
</a><li><a href="#How-can-I-quote-a-variable-to-use-in-a-regex%3f">How can I quote a variable to use in a regex?
  </a><li><a href="#What-is-%2fo-really-for%3f">What is /o really for?
 </a><li><a href="#How-do-I-use-a-regular-expression-to-strip-C-style-comments-from-a-file%3f">How do I use a regular expression to strip C-style comments from a file?</a><li><a href="#Can-I-use-Perl-regular-expressions-to-match-balanced-text%3f">Can I use Perl regular expressions to match balanced text?
 
  
   </a><li><a href="#What-does-it-mean-that-regexes-are-greedy%3f-How-can-I-get-around-it%3f">What does it mean that regexes are greedy? How can I get around it?
 </a><li><a href="#How-do-I-process-each-word-on-each-line%3f">How do I process each word on each line?
</a><li><a href="#How-can-I-print-out-a-word-frequency-or-line-frequency-summary%3f">How can I print out a word-frequency or line-frequency summary?</a><li><a href="#How-can-I-do-approximate-matching%3f">How can I do approximate matching?
 </a><li><a href="#How-do-I-efficiently-match-many-regular-expressions-at-once%3f">How do I efficiently match many regular expressions at once?
 
</a><li><a href="#Why-don't-word-boundary-searches-with-%5cb-work-for-me%3f">Why don't word-boundary searches with \b work for me?
</a><li><a href="#Why-does-using-%24%26%2c-%24%60%2c-or-%24'-slow-my-program-down%3f">Why does using $&, $`, or $' slow my program down?
     </a><li><a href="#What-good-is-%5cG-in-a-regular-expression%3f">What good is \G in a regular expression?
</a><li><a href="#Are-Perl-regexes-DFAs-or-NFAs%3f-Are-they-POSIX-compliant%3f">Are Perl regexes DFAs or NFAs? Are they POSIX compliant?
  </a><li><a href="#What's-wrong-with-using-grep-in-a-void-context%3f">What's wrong with using grep in a void context?
</a><li><a href="#How-can-I-match-strings-with-multibyte-characters%3f">How can I match strings with multibyte characters?
 
  </a><li><a href="#How-do-I-match-a-regular-expression-that's-in-a-variable%3f">How do I match a regular expression that's in a variable?
    
 </a></ul><li><a href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a></ul>
    </div>
    <div id="page_index_footer" class="hud_footer">
      <div id="page_index_bottomleft" class="hud_bottomleft"></div>
      <div id="page_index_bottom" class="hud_bottom"><span class="hud_span_bottom"></span></div>
      <div id="page_index_resize" class="hud_resize"></div>
    </div>
  </div>


	    &nbsp;
          </div>
          <div id="content_footer">
          </div>
        </div>
        <div class="clear"></div>
      </div>
      
    <div id="footer">
      <div id="footer_content">
        <div id="footer_strapline">
          perldoc.perl.org - Official documentation for the Perl programming language
        </div>
        <div id="footer_links">
          <div id="address">
            <p class="name">Contact details</p>
            <p class="address">
	      Site maintained by <a href="mailto:jj@jonallen.info">Jon Allen (JJ)</a><br>
	    </p>
            <p class="contact">
              Documentation maintained by the <a href="http://lists.cpan.org/showlist.cgi?name=perl5-porters">Perl 5 Porters</a>
            </p>
          </div>
          <ul class="f1">
            <li>Manual
              <ul class="f2">
                <li><a href="index-overview.html">Overview</a>
                <li><a href="index-tutorials.html">Tutorials</a>
                <li><a href="index-faq.html">FAQs</a>
                <li><a href="index-history.html">Changes</a>
              </ul>
            <li>Reference
              <ul class="f2">
                <li><a href="index-language.html">Language</a>
                <li><a href="index-functions.html">Functions</a>
                <li><a href="perlop.html">Operators</a>
                <li><a href="perlvar.html">Variables</a>
              </ul>
            <li>Modules
              <ul class="f2">
                <li><a href="index-modules-A.html">Modules</a>
                <li><a href="index-pragmas.html">Pragmas</a>
                <li><a href="index-utilities.html">Utilities</a>
              </ul>
            <li>Misc
              <ul class="f2">
                <li><a href="index-licence.html">License</a>
                <li><a href="index-internals.html">Internals</a>
                <li><a href="index-platforms.html">Platforms</a>
              </ul>          </ul>
          <div class="clear"></div>
        </div>
      </div>
      <div id="footer_end">
      </div>
    </div>
      
    </div>
      <script language="JavaScript" type="text/javascript" src="static/exploreperl.js"></script>
      <script language="JavaScript" src="static/combined-20100403.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
  perldoc.setPath(0);
  perldoc.pageName    = 'perlfaq6';
  perldoc.pageAddress = 'perlfaq6.html';
  perldoc.contentPage = 1;
  explorePerl.render();
  explorePerl.addEvents('explore_anchor');
</script>
    
  </body>
</html>