perlfaq4.html 285 KB
Newer Older
1 2 3
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
4 5
<head>
  <title>perlfaq4 - perldoc.perl.org</title>
6 7
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta http-equiv="Content-Language" content="en-gb">
8 9 10
  <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">
11 12
</head>

13 14 15 16 17 18 19
<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>
20 21 22 23 24 25 26 27 28
	<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>
29
      </div>
30 31 32 33
      
      <div id="body">
        <div id="left_column">
          <div class="side_group">
34 35
            
	    <div class="side_panel doc_panel">
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
              <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>
54
                <li><a href="index-internals.html">Internals</a>
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
                <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>
277 278 279 280 281 282 283 284
            
	      <div class="side_panel doc_panel">
		<p>Tools</p>
		<ul>
		  <li><a href="preferences.html">Preferences</a>
		</ul>
	      </div>
            
285 286 287 288 289 290 291 292 293
          </div>
        </div>
        <div id="centre_column">
          <div id="content_header">
            <div id="title_bar">
              <div id="page_name">
                <h1>perlfaq4</h1>
              </div>
              <div id="perl_version">
294
                Perl 5 version 26.0 documentation
295
              </div>
296
              <div class="page_links" id="page_links_top">
297 298
                <a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
		
299 300
              </div>
	      <div class="page_links" id="page_links_bottom">
301
		
302
                  <a href="#" id="page_index_toggle">Show page index</a> &bull;
303
		
304 305 306 307 308 309 310
                <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>
311 312 313 314 315 316 317 318 319 320 321
            </div>
            <div id="breadcrumbs">
                
    <a href="index.html">Home</a> &gt;
    
      
        <a href="index-faq.html">FAQs</a> &gt;
      
    
    perlfaq4
  
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
            </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>
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

	    <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>
  
379 380 381 382 383
	    <div id="from_search"></div>
            <h1>perlfaq4</h1>


  <!--    -->
384
<ul><li><a href="#NAME">NAME</a><li><a href="#VERSION">VERSION</a><li><a href="#DESCRIPTION">DESCRIPTION</a><li><a href="#Data%3a-Numbers">Data: Numbers</a><ul><li><a href="#Why-am-I-getting-long-decimals-(eg%2c-19.9499999999999)-instead-of-the-numbers-I-should-be-getting-(eg%2c-19.95)%3f">Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</a><li><a href="#Why-is-int()-broken%3f">Why is int() broken?</a><li><a href="#Why-isn't-my-octal-data-interpreted-correctly%3f">Why isn't my octal data interpreted correctly?</a><li><a href="#Does-Perl-have-a-round()-function%3f-What-about-ceil()-and-floor()%3f-Trig-functions%3f">Does Perl have a round() function? What about ceil() and floor()? Trig functions?</a><li><a href="#How-do-I-convert-between-numeric-representations%2fbases%2fradixes%3f">How do I convert between numeric representations/bases/radixes?</a><li><a href="#Why-doesn't-%26-work-the-way-I-want-it-to%3f">Why doesn't & work the way I want it to?</a><li><a href="#How-do-I-multiply-matrices%3f">How do I multiply matrices?</a><li><a href="#How-do-I-perform-an-operation-on-a-series-of-integers%3f">How do I perform an operation on a series of integers?</a><li><a href="#How-can-I-output-Roman-numerals%3f">How can I output Roman numerals?</a><li><a href="#Why-aren't-my-random-numbers-random%3f">Why aren't my random numbers random?</a><li><a href="#How-do-I-get-a-random-number-between-X-and-Y%3f">How do I get a random number between X and Y?</a></ul><li><a href="#Data%3a-Dates">Data: Dates</a><ul><li><a href="#How-do-I-find-the-day-or-week-of-the-year%3f">How do I find the day or week of the year?</a><li><a href="#How-do-I-find-the-current-century-or-millennium%3f">How do I find the current century or millennium?</a><li><a href="#How-can-I-compare-two-dates-and-find-the-difference%3f">How can I compare two dates and find the difference?</a><li><a href="#How-can-I-take-a-string-and-turn-it-into-epoch-seconds%3f">How can I take a string and turn it into epoch seconds?</a><li><a href="#How-can-I-find-the-Julian-Day%3f">How can I find the Julian Day?</a><li><a href="#How-do-I-find-yesterday's-date%3f">How do I find yesterday's date?
385
    
386
   
387
</a><li><a href="#Does-Perl-have-a-Year-2000-or-2038-problem%3f-Is-Perl-Y2K-compliant%3f">Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?</a></ul><li><a href="#Data%3a-Strings">Data: Strings</a><ul><li><a href="#How-do-I-validate-input%3f">How do I validate input?</a><li><a href="#How-do-I-unescape-a-string%3f">How do I unescape a string?</a><li><a href="#How-do-I-remove-consecutive-pairs-of-characters%3f">How do I remove consecutive pairs of characters?</a><li><a href="#How-do-I-expand-function-calls-in-a-string%3f">How do I expand function calls in a string?</a><li><a href="#How-do-I-find-matching%2fnesting-anything%3f">How do I find matching/nesting anything?</a><li><a href="#How-do-I-reverse-a-string%3f">How do I reverse a string?</a><li><a href="#How-do-I-expand-tabs-in-a-string%3f">How do I expand tabs in a string?</a><li><a href="#How-do-I-reformat-a-paragraph%3f">How do I reformat a paragraph?</a><li><a href="#How-can-I-access-or-change-N-characters-of-a-string%3f">How can I access or change N characters of a string?</a><li><a href="#How-do-I-change-the-Nth-occurrence-of-something%3f">How do I change the Nth occurrence of something?</a><li><a href="#How-can-I-count-the-number-of-occurrences-of-a-substring-within-a-string%3f">How can I count the number of occurrences of a substring within a string?</a><li><a href="#How-do-I-capitalize-all-the-words-on-one-line%3f">How do I capitalize all the words on one line?
388
   </a><li><a href="#How-can-I-split-a-%5bcharacter%5d-delimited-string-except-when-inside-%5bcharacter%5d%3f">How can I split a [character]-delimited string except when inside [character]?</a><li><a href="#How-do-I-strip-blank-space-from-the-beginning%2fend-of-a-string%3f">How do I strip blank space from the beginning/end of a string?</a><li><a href="#How-do-I-pad-a-string-with-blanks-or-pad-a-number-with-zeroes%3f">How do I pad a string with blanks or pad a number with zeroes?</a><li><a href="#How-do-I-extract-selected-columns-from-a-string%3f">How do I extract selected columns from a string?</a><li><a href="#How-do-I-find-the-soundex-value-of-a-string%3f">How do I find the soundex value of a string?</a><li><a href="#How-can-I-expand-variables-in-text-strings%3f">How can I expand variables in text strings?</a><li><a href="#What's-wrong-with-always-quoting-%22%24vars%22%3f">What's wrong with always quoting "$vars"?</a><li><a href="#Why-don't-my-%3c%3cHERE-documents-work%3f">Why don't my <<HERE documents work?</a></ul><li><a href="#Data%3a-Arrays">Data: Arrays</a><ul><li><a href="#What-is-the-difference-between-a-list-and-an-array%3f">What is the difference between a list and an array?</a><li><a href="#What-is-the-difference-between-%24array%5b1%5d-and-%40array%5b1%5d%3f">What is the difference between $array[1] and @array[1]?</a><li><a href="#How-can-I-remove-duplicate-elements-from-a-list-or-array%3f">How can I remove duplicate elements from a list or array?</a><li><a href="#How-can-I-tell-whether-a-certain-element-is-contained-in-a-list-or-array%3f">How can I tell whether a certain element is contained in a list or array?</a><li><a href="#How-do-I-compute-the-difference-of-two-arrays%3f-How-do-I-compute-the-intersection-of-two-arrays%3f">How do I compute the difference of two arrays? How do I compute the intersection of two arrays?</a><li><a href="#How-do-I-test-whether-two-arrays-or-hashes-are-equal%3f">How do I test whether two arrays or hashes are equal?</a><li><a href="#How-do-I-find-the-first-array-element-for-which-a-condition-is-true%3f">How do I find the first array element for which a condition is true?</a><li><a href="#How-do-I-handle-linked-lists%3f">How do I handle linked lists?</a><li><a href="#How-do-I-handle-circular-lists%3f">How do I handle circular lists?
389 390 391 392 393
   
 </a><li><a href="#How-do-I-shuffle-an-array-randomly%3f">How do I shuffle an array randomly?</a><li><a href="#How-do-I-process%2fmodify-each-element-of-an-array%3f">How do I process/modify each element of an array?</a><li><a href="#How-do-I-select-a-random-element-from-an-array%3f">How do I select a random element from an array?</a><li><a href="#How-do-I-permute-N-elements-of-a-list%3f">How do I permute N elements of a list?
   
 </a><li><a href="#How-do-I-sort-an-array-by-(anything)%3f">How do I sort an array by (anything)?</a><li><a href="#How-do-I-manipulate-arrays-of-bits%3f">How do I manipulate arrays of bits?</a><li><a href="#Why-does-defined()-return-true-on-empty-arrays-and-hashes%3f">Why does defined() return true on empty arrays and hashes?</a></ul><li><a href="#Data%3a-Hashes-(Associative-Arrays)">Data: Hashes (Associative Arrays)</a><ul><li><a href="#How-do-I-process-an-entire-hash%3f">How do I process an entire hash?</a><li><a href="#How-do-I-merge-two-hashes%3f">How do I merge two hashes?
  </a><li><a href="#What-happens-if-I-add-or-remove-keys-from-a-hash-while-iterating-over-it%3f">What happens if I add or remove keys from a hash while iterating over it?</a><li><a href="#How-do-I-look-up-a-hash-element-by-value%3f">How do I look up a hash element by value?</a><li><a href="#How-can-I-know-how-many-entries-are-in-a-hash%3f">How can I know how many entries are in a hash?</a><li><a href="#How-do-I-sort-a-hash-(optionally-by-value-instead-of-key)%3f">How do I sort a hash (optionally by value instead of key)?</a><li><a href="#How-can-I-always-keep-my-hash-sorted%3f">How can I always keep my hash sorted?
394
</a><li><a href="#What's-the-difference-between-%22delete%22-and-%22undef%22-with-hashes%3f">What's the difference between "delete" and "undef" with hashes?</a><li><a href="#Why-don't-my-tied-hashes-make-the-defined%2fexists-distinction%3f">Why don't my tied hashes make the defined/exists distinction?</a><li><a href="#How-do-I-reset-an-each()-operation-part-way-through%3f">How do I reset an each() operation part-way through?</a><li><a href="#How-can-I-get-the-unique-keys-from-two-hashes%3f">How can I get the unique keys from two hashes?</a><li><a href="#How-can-I-store-a-multidimensional-array-in-a-DBM-file%3f">How can I store a multidimensional array in a DBM file?</a><li><a href="#How-can-I-make-my-hash-remember-the-order-I-put-elements-into-it%3f">How can I make my hash remember the order I put elements into it?</a><li><a href="#Why-does-passing-a-subroutine-an-undefined-element-in-a-hash-create-it%3f">Why does passing a subroutine an undefined element in a hash create it?</a><li><a href="#How-can-I-make-the-Perl-equivalent-of-a-C-structure%2fC%2b%2b-class%2fhash-or-array-of-hashes-or-arrays%3f">How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?</a><li><a href="#How-can-I-use-a-reference-as-a-hash-key%3f">How can I use a reference as a hash key?</a><li><a href="#How-can-I-check-if-a-key-exists-in-a-multilevel-hash%3f">How can I check if a key exists in a multilevel hash?</a><li><a href="#How-can-I-prevent-addition-of-unwanted-keys-into-a-hash%3f">How can I prevent addition of unwanted keys into a hash?</a></ul><li><a href="#Data%3a-Misc">Data: Misc</a><ul><li><a href="#How-do-I-handle-binary-data-correctly%3f">How do I handle binary data correctly?</a><li><a href="#How-do-I-determine-whether-a-scalar-is-a-number%2fwhole%2finteger%2ffloat%3f">How do I determine whether a scalar is a number/whole/integer/float?</a><li><a href="#How-do-I-keep-persistent-data-across-program-calls%3f">How do I keep persistent data across program calls?</a><li><a href="#How-do-I-print-out-or-copy-a-recursive-data-structure%3f">How do I print out or copy a recursive data structure?</a><li><a href="#How-do-I-define-methods-for-every-class%2fobject%3f">How do I define methods for every class/object?</a><li><a href="#How-do-I-verify-a-credit-card-checksum%3f">How do I verify a credit card checksum?</a><li><a href="#How-do-I-pack-arrays-of-doubles-or-floats-for-XS-code%3f">How do I pack arrays of doubles or floats for XS code?</a></ul><li><a href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a></ul><a name="NAME"></a><h1>NAME</h1>
395
<p>perlfaq4 - Data Manipulation</p>
396
<a name="VERSION"></a><h1>VERSION</h1>
397
<p>version 5.021011</p>
398 399 400 401 402
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>This section of the FAQ answers questions related to manipulating
numbers, dates, strings, arrays, hashes, and miscellaneous data issues.</p>
<a name="Data%3a-Numbers"></a><h1>Data: Numbers</h1>
<a name="Why-am-I-getting-long-decimals-(eg%2c-19.9499999999999)-instead-of-the-numbers-I-should-be-getting-(eg%2c-19.95)%3f"></a><h2>Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</h2>
403 404 405
<p>For the long explanation, see David Goldberg's "What Every Computer
Scientist Should Know About Floating-Point Arithmetic"
(<a href="http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf">http://web.cse.msu.edu/~cse320/Documents/FloatingPoint.pdf</a>).</p>
406 407
<p>Internally, your computer represents floating-point numbers in binary.
Digital (as in powers of two) computers cannot store all numbers
408
exactly. Some real numbers lose precision in the process. This is a
409 410 411 412 413
problem with how computers store numbers and affects all computer
languages, not just Perl.</p>
<p><a href="perlnumber.html">perlnumber</a> shows the gory details of number representations and
conversions.</p>
<p>To limit the number of decimal places in your numbers, you can use the
414 415 416 417
<code class="inline"><a class="l_k" href="functions/printf.html">printf</a></code> or <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf</a></code> function. See
<a href="perlop.html#Floating-point-Arithmetic">Floating-point Arithmetic in perlop</a> for more details.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%.2f&quot;</span><span class="cm">,</span> <span class="n">10</span>/<span class="n">3</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$number</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a> <span class="q">&quot;%.2f&quot;</span><span class="cm">,</span> <span class="n">10</span>/<span class="n">3</span><span class="sc">;</span></li></ol></pre><a name="Why-is-int()-broken%3f"></a><h2>Why is int() broken?</h2>
<p>Your <code class="inline"><a class="l_k" href="functions/int.html">int()</a></code> is most probably working just fine. It's the numbers that
418 419
aren't quite what you think.</p>
<p>First, see the answer to "Why am I getting long decimals
420
(eg, 19.9499999999999) instead of the numbers I should be getting
421
(eg, 19.95)?".</p>
422
<p>For example, this</p>
423
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/int.html">int</a><span class="s">(</span><span class="n">0.6</span>/<span class="n">0.2</span>-<span class="n">2</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li></ol></pre><p>will in most computers print 0, not 1, because even such simple
424
numbers as 0.6 and 0.2 cannot be presented exactly by floating-point
425
numbers. What you think in the above as 'three' is really more like
426
2.9999999999999995559.</p>
427
<a name="Why-isn't-my-octal-data-interpreted-correctly%3f"></a><h2>Why isn't my octal data interpreted correctly?</h2>
428
<p>(contributed by brian d foy)</p>
429
<p>You're probably trying to convert a string to a number, which Perl only
430 431 432
converts as a decimal number. When Perl converts a string to a number, it
ignores leading spaces and zeroes, then assumes the rest of the digits
are in base 10:</p>
433
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$string</span> = <span class="q">&#39;0644&#39;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">$string</span> + <span class="n">0</span><span class="sc">;</span>  <span class="c"># prints 644</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">$string</span> + <span class="n">44</span><span class="sc">;</span> <span class="c"># prints 688, certainly not octal!</span></li></ol></pre><p>This problem usually involves one of the Perl built-ins that has the
434
same name a Unix command that uses octal numbers as arguments on the
435
command line. In this example, <code class="inline"><a class="l_k" href="functions/chmod.html">chmod</a></code> on the command line knows that
436
its first argument is octal because that's what it does:</p>
437
<pre class="verbatim"><ol><li>    <span class="i">%prompt</span>&gt; <a class="l_k" href="functions/chmod.html">chmod</a> <span class="n">644</span> <span class="w">file</span></li></ol></pre><p>If you want to use the same literal digits (644) in Perl, you have to tell
438 439 440
Perl to treat them as octal numbers either by prefixing the digits with
a <code class="inline"><span class="n">0</span></code>
 or using <code class="inline"><a class="l_k" href="functions/oct.html">oct</a></code>:</p>
441
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chmod.html">chmod</a><span class="s">(</span>     <span class="n">0644</span><span class="cm">,</span> <span class="i">$filename</span> <span class="s">)</span><span class="sc">;</span>  <span class="c"># right, has leading zero</span></li><li>    <a class="l_k" href="functions/chmod.html">chmod</a><span class="s">(</span> <a class="l_k" href="functions/oct.html">oct</a><span class="s">(</span><span class="n">644</span><span class="s">)</span><span class="cm">,</span> <span class="i">$filename</span> <span class="s">)</span><span class="sc">;</span>  <span class="c"># also correct</span></li></ol></pre><p>The problem comes in when you take your numbers from something that Perl
442 443
thinks is a string, such as a command line argument in <code class="inline"><span class="i">@ARGV</span></code>
:</p>
444
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/chmod.html">chmod</a><span class="s">(</span> <span class="i">$ARGV</span>[<span class="n">0</span>]<span class="cm">,</span>      <span class="i">$filename</span> <span class="s">)</span><span class="sc">;</span>  <span class="c"># wrong, even if &quot;0644&quot;</span></li><li></li><li>    <a class="l_k" href="functions/chmod.html">chmod</a><span class="s">(</span> <a class="l_k" href="functions/oct.html">oct</a><span class="s">(</span><span class="i">$ARGV</span>[<span class="n">0</span>]<span class="s">)</span><span class="cm">,</span> <span class="i">$filename</span> <span class="s">)</span><span class="sc">;</span>  <span class="c"># correct, treat string as octal</span></li></ol></pre><p>You can always check the value you're using by printing it in octal
445 446
notation to ensure it matches what you think it should be. Print it
in octal  and decimal format:</p>
447 448
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;0%o %d&quot;</span><span class="cm">,</span> <span class="i">$number</span><span class="cm">,</span> <span class="i">$number</span><span class="sc">;</span></li></ol></pre><a name="Does-Perl-have-a-round()-function%3f-What-about-ceil()-and-floor()%3f-Trig-functions%3f"></a><h2>Does Perl have a round() function? What about ceil() and floor()? Trig functions?</h2>
<p>Remember that <code class="inline"><a class="l_k" href="functions/int.html">int()</a></code> merely truncates toward 0. For rounding to a
449 450
certain number of digits, <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf()</a></code> or <code class="inline"><a class="l_k" href="functions/printf.html">printf()</a></code> is usually the
easiest route.</p>
451
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/printf.html">printf</a><span class="s">(</span><span class="q">&quot;%.3f&quot;</span><span class="cm">,</span> <span class="n">3.1415926535</span><span class="s">)</span><span class="sc">;</span>   <span class="c"># prints 3.142</span></li></ol></pre><p>The <a href="POSIX.html">POSIX</a> module (part of the standard Perl distribution)
452 453 454 455
implements <code class="inline"><span class="i">ceil</span><span class="s">(</span><span class="s">)</span></code>
, <code class="inline"><span class="i">floor</span><span class="s">(</span><span class="s">)</span></code>
, and a number of other mathematical
and trigonometric functions.</p>
456 457
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$ceil</span>   = <span class="i">ceil</span><span class="s">(</span><span class="n">3.5</span><span class="s">)</span><span class="sc">;</span>   <span class="c"># 4</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$floor</span>  = <span class="i">floor</span><span class="s">(</span><span class="n">3.5</span><span class="s">)</span><span class="sc">;</span>  <span class="c"># 3</span></li></ol></pre><p>In 5.000 to 5.003 perls, trigonometry was done in the <a href="Math/Complex.html">Math::Complex</a>
module. With 5.004, the <a href="Math/Trig.html">Math::Trig</a> module (part of the standard Perl
458
distribution) implements the trigonometric functions. Internally it
459
uses the <a href="Math/Complex.html">Math::Complex</a> module and some functions can break out from
460 461 462
the real axis into the complex plane, for example the inverse sine of
2.</p>
<p>Rounding in financial applications can have serious implications, and
463
the rounding method used should be specified precisely. In these
464 465
cases, it probably pays not to trust whichever system of rounding is
being used by Perl, but instead to implement the rounding function you
466
need yourself.</p>
467
<p>To see why, notice how you'll still have an issue on half-way-point
468
alternation:</p>
469
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/for.html">for</a> <span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$i</span> = <span class="n">0</span><span class="sc">;</span> <span class="i">$i</span> &lt; <span class="n">1.01</span><span class="sc">;</span> <span class="i">$i</span> += <span class="n">0.05</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;%.1f &quot;</span><span class="cm">,</span><span class="i">$i</span><span class="s">}</span></li><li></li><li>    <span class="n">0.0</span> <span class="n">0.1</span> <span class="n">0.1</span> <span class="n">0.2</span> <span class="n">0.2</span> <span class="n">0.2</span> <span class="n">0.3</span> <span class="n">0.3</span> <span class="n">0.4</span> <span class="n">0.4</span> <span class="n">0.5</span> <span class="n">0.5</span> <span class="n">0.6</span> <span class="n">0.7</span> <span class="n">0.7</span></li><li>    <span class="n">0.8</span> <span class="n">0.8</span> <span class="n">0.9</span> <span class="n">0.9</span> <span class="n">1.0</span> <span class="n">1.0</span></li></ol></pre><p>Don't blame Perl. It's the same as in C. IEEE says we have to do
470
this. Perl numbers whose absolute values are integers under 2**31 (on
471
32-bit machines) will work pretty much like mathematical integers.
472
Other numbers are not guaranteed.</p>
473
<a name="How-do-I-convert-between-numeric-representations%2fbases%2fradixes%3f"></a><h2>How do I convert between numeric representations/bases/radixes?</h2>
474
<p>As always with Perl there is more than one way to do it. Below are a
475
few examples of approaches to making common conversions between number
476
representations. This is intended to be representational rather than
477
exhaustive.</p>
478 479
<p>Some of the examples later in <a href="perlfaq4.html">perlfaq4</a> use the <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a>
module from CPAN. The reason you might choose <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a> over the
480
perl built-in functions is that it works with numbers of ANY size,
481 482
that it is optimized for speed on some operations, and for at least
some programmers the notation might be familiar.</p>
483 484
<ul>
<li><a name="How-do-I-convert-hexadecimal-into-decimal"></a><b>How do I convert hexadecimal into decimal</b>
485
<p>Using perl's built in conversion of <code class="inline"><span class="n">0</span>x</code>
486
 notation:</p>
487 488 489
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <span class="n">0xDEADBEEF</span><span class="sc">;</span></li></ol></pre><p>Using the <code class="inline"><a class="l_k" href="functions/hex.html">hex</a></code> function:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <a class="l_k" href="functions/hex.html">hex</a><span class="s">(</span><span class="q">&quot;DEADBEEF&quot;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;N&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;H8&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="q">&quot;0&quot;</span> x <span class="n">8</span> . <span class="q">&quot;DEADBEEF&quot;</span><span class="cm">,</span> <span class="n">-8</span><span class="s">)</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using the CPAN module <code class="inline"><span class="w">Bit::Vector</span></code>
490
:</p>
491
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Bit::Vector</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new_Hex</span><span class="s">(</span><span class="n">32</span><span class="cm">,</span> <span class="q">&quot;DEADBEEF&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <span class="i">$vec</span><span class="i">-&gt;to_Dec</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre></li>
492
<li><a name="How-do-I-convert-from-decimal-to-hexadecimal"></a><b>How do I convert from decimal to hexadecimal</b>
493
<p>Using <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf</a></code>:</p>
494 495 496 497
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$hex</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%X&quot;</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="sc">;</span> <span class="c"># upper case A-F</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$hex</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%x&quot;</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="sc">;</span> <span class="c"># lower case a-f</span></li></ol></pre><p>Using <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$hex</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;H*&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;N&quot;</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Bit::Vector</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new_Dec</span><span class="s">(</span><span class="n">32</span><span class="cm">,</span> <span class="n">-559038737</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$hex</span> = <span class="i">$vec</span><span class="i">-&gt;to_Hex</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>And <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a> supports odd bit counts:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Bit::Vector</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new_Dec</span><span class="s">(</span><span class="n">33</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$vec</span><span class="i">-&gt;Resize</span><span class="s">(</span><span class="n">32</span><span class="s">)</span><span class="sc">;</span> <span class="c"># suppress leading 0 if unwanted</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$hex</span> = <span class="i">$vec</span><span class="i">-&gt;to_Hex</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre></li>
498
<li><a name="How-do-I-convert-from-octal-to-decimal"></a><b>How do I convert from octal to decimal</b>
499
<p>Using Perl's built in conversion of numbers with leading zeros:</p>
500 501 502
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <span class="n">033653337357</span><span class="sc">;</span> <span class="c"># note the leading 0!</span></li></ol></pre><p>Using the <code class="inline"><a class="l_k" href="functions/oct.html">oct</a></code> function:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <a class="l_k" href="functions/oct.html">oct</a><span class="s">(</span><span class="q">&quot;33653337357&quot;</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Bit::Vector</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new</span><span class="s">(</span><span class="n">32</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$vec</span><span class="i">-&gt;Chunk_List_Store</span><span class="s">(</span><span class="n">3</span><span class="cm">,</span> <a class="l_k" href="functions/split.html">split</a><span class="s">(</span><span class="q">//</span><span class="cm">,</span> <a class="l_k" href="functions/reverse.html">reverse</a> <span class="q">&quot;33653337357&quot;</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">$dec</span> = <span class="i">$vec</span><span class="i">-&gt;to_Dec</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre></li>
503
<li><a name="How-do-I-convert-from-decimal-to-octal"></a><b>How do I convert from decimal to octal</b>
504
<p>Using <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf</a></code>:</p>
505 506
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$oct</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%o&quot;</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Bit::Vector</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new_Dec</span><span class="s">(</span><span class="n">32</span><span class="cm">,</span> <span class="n">-559038737</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$oct</span> = <a class="l_k" href="functions/reverse.html">reverse</a> <a class="l_k" href="functions/join.html">join</a><span class="s">(</span><span class="q">&#39;&#39;</span><span class="cm">,</span> <span class="i">$vec</span><span class="i">-&gt;Chunk_List_Read</span><span class="s">(</span><span class="n">3</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li></ol></pre></li>
507 508
<li><a name="How-do-I-convert-from-binary-to-decimal"></a><b>How do I convert from binary to decimal</b>
<p>Perl 5.6 lets you write binary numbers directly with
509
the <code class="inline">0b</code> notation:</p>
510 511 512 513 514
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$number</span> = <span class="n">0b10110110</span><span class="sc">;</span></li></ol></pre><p>Using <code class="inline"><a class="l_k" href="functions/oct.html">oct</a></code>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$input</span> = <span class="q">&quot;10110110&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$decimal</span> = <a class="l_k" href="functions/oct.html">oct</a><span class="s">(</span> <span class="q">&quot;0b$input&quot;</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/ord.html">ord</a></code>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$decimal</span> = <a class="l_k" href="functions/ord.html">ord</a><span class="s">(</span><a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&#39;B8&#39;</span><span class="cm">,</span> <span class="q">&#39;10110110&#39;</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> for larger strings:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$int</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;N&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;B32&quot;</span><span class="cm">,</span></li><li>    <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="q">&quot;0&quot;</span> x <span class="n">32</span> . <span class="q">&quot;11110101011011011111011101111&quot;</span><span class="cm">,</span> <span class="n">-32</span><span class="s">)</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">$dec</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%d&quot;</span><span class="cm">,</span> <span class="i">$int</span><span class="s">)</span><span class="sc">;</span></li><li></li><li>    <span class="c"># substr() is used to left-pad a 32-character string with zeros.</span></li></ol></pre><p>Using <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new_Bin</span><span class="s">(</span><span class="n">32</span><span class="cm">,</span> <span class="q">&quot;11011110101011011011111011101111&quot;</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$dec</span> = <span class="i">$vec</span><span class="i">-&gt;to_Dec</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre></li>
515
<li><a name="How-do-I-convert-from-decimal-to-binary"></a><b>How do I convert from decimal to binary</b>
516
<p>Using <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf</a></code> (perl 5.6+):</p>
517 518 519
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$bin</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%b&quot;</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$bin</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">&quot;B*&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;N&quot;</span><span class="cm">,</span> <span class="n">3735928559</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Using <a href="http://search.cpan.org/perldoc/Bit::Vector">Bit::Vector</a>:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Bit::Vector</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$vec</span> = <span class="w">Bit::Vector</span><span class="w">-&gt;new_Dec</span><span class="s">(</span><span class="n">32</span><span class="cm">,</span> <span class="n">-559038737</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$bin</span> = <span class="i">$vec</span><span class="i">-&gt;to_Bin</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The remaining transformations (e.g. hex -&gt; oct, bin -&gt; hex, etc.)
520 521 522
are left as an exercise to the inclined reader.</p>
</li>
</ul>
523 524
<a name="Why-doesn't-%26-work-the-way-I-want-it-to%3f"></a><h2>Why doesn't &amp; work the way I want it to?</h2>
<p>The behavior of binary arithmetic operators depends on whether they're
525
used on numbers or strings. The operators treat a string as a series
526 527 528
of bits and work with that (the string <code class="inline"><span class="q">&quot;3&quot;</span></code>
 is the bit pattern
<code class="inline"><span class="n">00110011</span></code>
529
). The operators work with the binary form of a number
530 531 532 533
(the number <code class="inline"><span class="n">3</span></code>
 is treated as the bit pattern <code class="inline"><span class="n">00000011</span></code>
).</p>
<p>So, saying <code class="inline"><span class="n">11</span> &amp; <span class="n">3</span></code>
534
 performs the "and" operation on numbers (yielding
535
<code class="inline"><span class="n">3</span></code>
536
). Saying <code class="inline"><span class="q">&quot;11&quot;</span> &amp; <span class="q">&quot;3&quot;</span></code>
537
 performs the "and" operation on strings
538 539 540 541
(yielding <code class="inline"><span class="q">&quot;1&quot;</span></code>
).</p>
<p>Most problems with <code class="inline"><span class="i">&amp;</span></code>
 and <code class="inline">|</code> arise because the programmer thinks
542
they have a number but really it's a string or vice versa. To avoid this,
543 544 545 546
stringify the arguments explicitly (using <code class="inline"><span class="q">&quot;&quot;</span></code>
 or <code class="inline"><a class="l_k" href="functions/qq.html">qq()</a></code>) or convert them
to numbers explicitly (using <code class="inline"><span class="n">0</span>+<span class="i">$arg</span></code>
). The rest arise because
547
the programmer says:</p>
548
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span><span class="q">&quot;\020\020&quot;</span> &amp; <span class="q">&quot;\101\101&quot;</span><span class="s">)</span> <span class="s">{</span></li><li>        <span class="c"># ...</span></li><li>    <span class="s">}</span></li></ol></pre><p>but a string consisting of two null bytes (the result of <code class="inline"><span class="q">&quot;\020\020&quot;</span>
549
&amp; <span class="q">&quot;\101\101&quot;</span></code>
550 551 552 553
) is not a false value in Perl. You need:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/if.html">if</a> <span class="s">(</span> <span class="s">(</span><span class="q">&quot;\020\020&quot;</span> &amp; <span class="q">&quot;\101\101&quot;</span><span class="s">)</span> !~ <span class="q">/[^\000]/</span><span class="s">)</span> <span class="s">{</span></li><li>        <span class="c"># ...</span></li><li>    <span class="s">}</span></li></ol></pre><a name="How-do-I-multiply-matrices%3f"></a><h2>How do I multiply matrices?</h2>
<p>Use the <a href="http://search.cpan.org/perldoc/Math::Matrix">Math::Matrix</a> or <a href="http://search.cpan.org/perldoc/Math::MatrixReal">Math::MatrixReal</a> modules (available from CPAN)
or the <a href="http://search.cpan.org/perldoc/PDL">PDL</a> extension (also available from CPAN).</p>
554 555 556
<a name="How-do-I-perform-an-operation-on-a-series-of-integers%3f"></a><h2>How do I perform an operation on a series of integers?</h2>
<p>To call a function on each element in an array, and collect the
results, use:</p>
557 558
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@results</span> = <a class="l_k" href="functions/map.html">map</a> <span class="s">{</span> <span class="i">my_func</span><span class="s">(</span><span class="i">$_</span><span class="s">)</span> <span class="s">}</span> <span class="i">@array</span><span class="sc">;</span></li></ol></pre><p>For example:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@triple</span> = <a class="l_k" href="functions/map.html">map</a> <span class="s">{</span> <span class="n">3</span> * <span class="i">$_</span> <span class="s">}</span> <span class="i">@single</span><span class="sc">;</span></li></ol></pre><p>To call a function on each element of an array, but ignore the
559
results:</p>
560 561 562 563 564 565 566 567 568 569 570 571
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/foreach.html">foreach</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$iterator</span> <span class="s">(</span><span class="i">@array</span><span class="s">)</span> <span class="s">{</span></li><li>        <span class="i">some_func</span><span class="s">(</span><span class="i">$iterator</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>To call a function on each integer in a (small) range, you <b>can</b> use:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@results</span> = <a class="l_k" href="functions/map.html">map</a> <span class="s">{</span> <span class="i">some_func</span><span class="s">(</span><span class="i">$_</span><span class="s">)</span> <span class="s">}</span> <span class="s">(</span><span class="n">5</span> .. <span class="n">25</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>but you should be aware that in this form, the <code class="inline">..</code>
 operator
creates a list of all integers in the range, which can take a lot of
memory for large ranges. However, the problem does not occur when
using <code class="inline">..</code>
 within a <code class="inline">for</code>
 loop, because in that case the range
operator is optimized to <i>iterate</i> over the range, without creating
the entire list. So</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@results</span> = <span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/for.html">for</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$i</span> <span class="s">(</span><span class="n">5</span> .. <span class="n">500_005</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/push.html">push</a><span class="s">(</span><span class="i">@results</span><span class="cm">,</span> <span class="i">some_func</span><span class="s">(</span><span class="i">$i</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>or even</p>
<pre class="verbatim"><ol><li>   <a class="l_k" href="functions/push.html">push</a><span class="s">(</span><span class="i">@results</span><span class="cm">,</span> <span class="i">some_func</span><span class="s">(</span><span class="i">$_</span><span class="s">)</span><span class="s">)</span> <a class="l_k" href="functions/for.html">for</a> <span class="n">5</span> .. <span class="n">500_005</span><span class="sc">;</span></li></ol></pre><p>will not create an intermediate list of 500,000 integers.</p>
572 573
<a name="How-can-I-output-Roman-numerals%3f"></a><h2>How can I output Roman numerals?</h2>
<p>Get the <a href="http://www.cpan.org/modules/by-module/Roman">http://www.cpan.org/modules/by-module/Roman</a> module.</p>
574 575
<a name="Why-aren't-my-random-numbers-random%3f"></a><h2>Why aren't my random numbers random?</h2>
<p>If you're using a version of Perl before 5.004, you must call <code class="inline"><a class="l_k" href="functions/srand.html">srand</a></code>
576
once at the start of your program to seed the random number generator.</p>
577
<pre class="verbatim"><ol><li>     <a class="l_k" href="functions/BEGIN.html">BEGIN</a> <span class="s">{</span> <a class="l_k" href="functions/srand.html">srand</a><span class="s">(</span><span class="s">)</span> <a class="l_k" href="functions/if.html">if</a> <span class="i">$]</span> &lt; <span class="n">5.004</span> <span class="s">}</span></li></ol></pre><p>5.004 and later automatically call <code class="inline"><a class="l_k" href="functions/srand.html">srand</a></code> at the beginning. Don't
578 579
call <code class="inline"><a class="l_k" href="functions/srand.html">srand</a></code> more than once--you make your numbers less random,
rather than more.</p>
580
<p>Computers are good at being predictable and bad at being random
581
(despite appearances caused by bugs in your programs :-). The
582 583
<i>random</i> article in the "Far More Than You Ever Wanted To Know"
collection in <a href="http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz">http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</a>, courtesy
584
of Tom Phoenix, talks more about this. John von Neumann said, "Anyone
585
who attempts to generate random numbers by deterministic means is, of
586
course, living in a state of sin."</p>
587 588 589 590 591 592 593 594 595 596 597 598
<p>Perl relies on the underlying system for the implementation of
<code class="inline"><a class="l_k" href="functions/rand.html">rand</a></code> and <code class="inline"><a class="l_k" href="functions/srand.html">srand</a></code>; on some systems, the generated numbers are
not random enough (especially on Windows : see
<a href="http://www.perlmonks.org/?node_id=803632">http://www.perlmonks.org/?node_id=803632</a>).
Several CPAN modules in the <code class="inline"><span class="w">Math</span></code>
 namespace implement better
pseudorandom generators; see for example
<a href="http://search.cpan.org/perldoc/Math::Random::MT">Math::Random::MT</a> ("Mersenne Twister", fast), or
<a href="http://search.cpan.org/perldoc/Math::TrulyRandom">Math::TrulyRandom</a> (uses the imperfections in the system's
timer to generate random numbers, which is rather slow).
More algorithms for random numbers are described in
"Numerical Recipes in C" at <a href="http://www.nr.com/">http://www.nr.com/</a></p>
599
<a name="How-do-I-get-a-random-number-between-X-and-Y%3f"></a><h2>How do I get a random number between X and Y?</h2>
600
<p>To get a random number between two values, you can use the <code class="inline"><a class="l_k" href="functions/rand.html">rand()</a></code>
601
built-in to get a random number between 0 and 1. From there, you shift
602 603 604 605 606 607 608
that into the range that you want.</p>
<p><code class="inline"><a class="l_k" href="functions/rand.html">rand($x)</a></code> returns a number such that <code class="inline"><span class="n">0</span> &lt;= <a class="l_k" href="functions/rand.html">rand</a><span class="s">(</span><span class="i">$x</span><span class="s">)</span> &lt; <span class="i">$x</span></code>
. Thus
what you want to have perl figure out is a random number in the range
from 0 to the difference between your <i>X</i> and <i>Y</i>.</p>
<p>That is, to get a number between 10 and 15, inclusive, you want a
random number between 0 and 5 that you can then add to 10.</p>
609
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$number</span> = <span class="n">10</span> + <a class="l_k" href="functions/int.html">int</a> <a class="l_k" href="functions/rand.html">rand</a><span class="s">(</span> <span class="n">15</span>-<span class="n">10</span>+<span class="n">1</span> <span class="s">)</span><span class="sc">;</span> <span class="c"># ( 10,11,12,13,14, or 15 )</span></li></ol></pre><p>Hence you derive the following simple function to abstract
610
that. It selects a random integer between the two given
611
integers (inclusive). For example: <code class="inline"><span class="i">random_int_between</span><span class="s">(</span><span class="n">50</span><span class="cm">,</span><span class="n">120</span><span class="s">)</span></code>
612
.</p>
613
<pre class="verbatim"><ol><li><a name="random_int_between"></a>    sub <span class="m">random_int_between</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$min</span><span class="cm">,</span> <span class="i">$max</span><span class="s">)</span> = <span class="i">@_</span><span class="sc">;</span></li><li>        <span class="c"># Assumes that the two arguments are integers themselves!</span></li><li>        <a class="l_k" href="functions/return.html">return</a> <span class="i">$min</span> <a class="l_k" href="functions/if.html">if</a> <span class="i">$min</span> == <span class="i">$max</span><span class="sc">;</span></li><li>        <span class="s">(</span><span class="i">$min</span><span class="cm">,</span> <span class="i">$max</span><span class="s">)</span> = <span class="s">(</span><span class="i">$max</span><span class="cm">,</span> <span class="i">$min</span><span class="s">)</span>  <a class="l_k" href="functions/if.html">if</a>  <span class="i">$min</span> &gt; <span class="i">$max</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/return.html">return</a> <span class="i">$min</span> + <a class="l_k" href="functions/int.html">int</a> <a class="l_k" href="functions/rand.html">rand</a><span class="s">(</span><span class="n">1</span> + <span class="i">$max</span> - <span class="i">$min</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><a name="Data%3a-Dates"></a><h1>Data: Dates</h1>
614
<a name="How-do-I-find-the-day-or-week-of-the-year%3f"></a><h2>How do I find the day or week of the year?</h2>
615 616 617
<p>The day of the year is in the list returned
by the <code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code> function. Without an
argument <code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code> uses the current time.</p>
618
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$day_of_year</span> = <span class="s">(</span><a class="l_k" href="functions/localtime.html">localtime</a><span class="s">)</span>[<span class="n">7</span>]<span class="sc">;</span></li></ol></pre><p>The <a href="POSIX.html">POSIX</a> module can also format a date as the day of the year or
619
week of the year.</p>
620
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">qw/strftime/</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$day_of_year</span>  = <span class="w">strftime</span> <span class="q">&quot;%j&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/localtime.html">localtime</a><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$week_of_year</span> = <span class="w">strftime</span> <span class="q">&quot;%W&quot;</span><span class="cm">,</span> <a class="l_k" href="functions/localtime.html">localtime</a><span class="sc">;</span></li></ol></pre><p>To get the day of year for any date, use <a href="POSIX.html">POSIX</a>'s <code class="inline"><span class="w">mktime</span></code>
621
 to get
622
a time in epoch seconds for the argument to <code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code>.</p>
623
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">qw/mktime strftime/</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$week_of_year</span> = <span class="w">strftime</span> <span class="q">&quot;%W&quot;</span><span class="cm">,</span></li><li>        <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span> <span class="i">mktime</span><span class="s">(</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">18</span><span class="cm">,</span> <span class="n">11</span><span class="cm">,</span> <span class="n">87</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>You can also use <a href="Time/Piece.html">Time::Piece</a>, which comes with Perl and provides a
624
<code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code> that returns an object:</p>
625 626
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Time::Piece</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$day_of_year</span>  = <a class="l_k" href="functions/localtime.html">localtime</a><span class="i">-&gt;yday</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$week_of_year</span> = <a class="l_k" href="functions/localtime.html">localtime</a><span class="i">-&gt;week</span><span class="sc">;</span></li></ol></pre><p>The <a href="http://search.cpan.org/perldoc/Date::Calc">Date::Calc</a> module provides two functions to calculate these, too:</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Date::Calc</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$day_of_year</span>  = <span class="i">Day_of_Year</span><span class="s">(</span>  <span class="n">1987</span><span class="cm">,</span> <span class="n">12</span><span class="cm">,</span> <span class="n">18</span> <span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$week_of_year</span> = <span class="i">Week_of_Year</span><span class="s">(</span> <span class="n">1987</span><span class="cm">,</span> <span class="n">12</span><span class="cm">,</span> <span class="n">18</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-find-the-current-century-or-millennium%3f"></a><h2>How do I find the current century or millennium?</h2>
627
<p>Use the following simple functions:</p>
628
<pre class="verbatim"><ol><li><a name="get_century"></a>    sub <span class="m">get_century</span>    <span class="s">{</span></li><li>        <a class="l_k" href="functions/return.html">return</a> <a class="l_k" href="functions/int.html">int</a><span class="s">(</span><span class="s">(</span><span class="s">(</span><span class="s">(</span><a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><a class="l_k" href="functions/shift.html">shift</a> || <a class="l_k" href="functions/time.html">time</a><span class="s">)</span><span class="s">)</span>[<span class="n">5</span>] + <span class="n">1999</span><span class="s">)</span><span class="s">)</span>/<span class="n">100</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li><li></li><li><a name="get_millennium"></a>    sub <span class="m">get_millennium</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/return.html">return</a> <span class="n">1</span>+<a class="l_k" href="functions/int.html">int</a><span class="s">(</span><span class="s">(</span><span class="s">(</span><span class="s">(</span><a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><a class="l_k" href="functions/shift.html">shift</a> || <a class="l_k" href="functions/time.html">time</a><span class="s">)</span><span class="s">)</span>[<span class="n">5</span>] + <span class="n">1899</span><span class="s">)</span><span class="s">)</span>/<span class="n">1000</span><span class="s">)</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>On some systems, the <a href="POSIX.html">POSIX</a> module's <code class="inline"><span class="i">strftime</span><span class="s">(</span><span class="s">)</span></code>
629 630 631
 function has been
extended in a non-standard way to use a <code class="inline"><span class="i">%C</span></code>
 format, which they
632
sometimes claim is the "century". It isn't, because on most such
633
systems, this is only the first two digits of the four-digit year, and
634
thus cannot be used to determine reliably the current century or
635
millennium.</p>
636 637
<a name="How-can-I-compare-two-dates-and-find-the-difference%3f"></a><h2>How can I compare two dates and find the difference?</h2>
<p>(contributed by brian d foy)</p>
638
<p>You could just store all your dates as a number and then subtract.
639
Life isn't always that simple though.</p>
640
<p>The <a href="Time/Piece.html">Time::Piece</a> module, which comes with Perl, replaces <a href="functions/localtime.html">localtime</a>
641 642
with a version that returns an object. It also overloads the comparison
operators so you can compare them directly:</p>
643 644
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Time::Piece</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$date1</span> = <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span> <span class="i">$some_time</span> <span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$date2</span> = <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span> <span class="i">$some_other_time</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">$date1</span> &lt; <span class="i">$date2</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;The date was in the past\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>You can also get differences with a subtraction, which returns a
<a href="Time/Seconds.html">Time::Seconds</a> object:</p>
645
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$date_diff</span> = <span class="i">$date1</span> - <span class="i">$date2</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The difference is &quot;</span><span class="cm">,</span> <span class="i">$date_diff</span><span class="i">-&gt;days</span><span class="cm">,</span> <span class="q">&quot; days\n&quot;</span><span class="sc">;</span></li></ol></pre><p>If you want to work with formatted dates, the <a href="http://search.cpan.org/perldoc/Date::Manip">Date::Manip</a>,
646
<a href="http://search.cpan.org/perldoc/Date::Calc">Date::Calc</a>, or <a href="http://search.cpan.org/perldoc/DateTime">DateTime</a> modules can help you.</p>
647
<a name="How-can-I-take-a-string-and-turn-it-into-epoch-seconds%3f"></a><h2>How can I take a string and turn it into epoch seconds?</h2>
648
<p>If it's a regular enough string that it always has the same format,
649
you can split it up and pass the parts to <code class="inline"><span class="w">timelocal</span></code>
650
 in the standard
651 652
<a href="Time/Local.html">Time::Local</a> module. Otherwise, you should look into the <a href="http://search.cpan.org/perldoc/Date::Calc">Date::Calc</a>,
<a href="http://search.cpan.org/perldoc/Date::Parse">Date::Parse</a>, and <a href="http://search.cpan.org/perldoc/Date::Manip">Date::Manip</a> modules from CPAN.</p>
653 654
<a name="How-can-I-find-the-Julian-Day%3f"></a><h2>How can I find the Julian Day?</h2>
<p>(contributed by brian d foy and Dave Cross)</p>
655
<p>You can use the <a href="Time/Piece.html">Time::Piece</a> module, part of the Standard Library,
656
which can convert a date/time to a Julian Day:</p>
657 658
<pre class="verbatim"><ol><li>    <span class="i">$ perl</span> -<span class="w">MTime::Piece</span> -<a class="l_k" href="functions/le.html">le</a> <span class="q">&#39;print localtime-&gt;julian_day&#39;</span></li><li>    <span class="n">2455607.7959375</span></li></ol></pre><p>Or the modified Julian Day:</p>
<pre class="verbatim"><ol><li>    <span class="i">$ perl</span> -<span class="w">MTime::Piece</span> -<a class="l_k" href="functions/le.html">le</a> <span class="q">&#39;print localtime-&gt;mjd&#39;</span></li><li>    <span class="n">55607.2961226851</span></li></ol></pre><p>Or even the day of the year (which is what some people think of as a
659
Julian day):</p>
660 661
<pre class="verbatim"><ol><li>    <span class="i">$ perl</span> -<span class="w">MTime::Piece</span> -<a class="l_k" href="functions/le.html">le</a> <span class="q">&#39;print localtime-&gt;yday&#39;</span></li><li>    <span class="n">45</span></li></ol></pre><p>You can also do the same things with the <a href="http://search.cpan.org/perldoc/DateTime">DateTime</a> module:</p>
<pre class="verbatim"><ol><li>    <span class="i">$ perl</span> -<span class="w">MDateTime</span> -<a class="l_k" href="functions/le.html">le</a><span class="q">&#39;print DateTime-&gt;today-&gt;jd&#39;</span></li><li>    <span class="n">2453401.5</span></li><li>    <span class="i">$ perl</span> -<span class="w">MDateTime</span> -<a class="l_k" href="functions/le.html">le</a><span class="q">&#39;print DateTime-&gt;today-&gt;mjd&#39;</span></li><li>    <span class="n">53401</span></li><li>    <span class="i">$ perl</span> -<span class="w">MDateTime</span> -<a class="l_k" href="functions/le.html">le</a><span class="q">&#39;print DateTime-&gt;today-&gt;doy&#39;</span></li><li>    <span class="n">31</span></li></ol></pre><p>You can use the <a href="http://search.cpan.org/perldoc/Time::JulianDay">Time::JulianDay</a> module available on CPAN. Ensure
662
that you really want to find a Julian day, though, as many people have
663
different ideas about Julian days (see <a href="http://www.hermetic.ch/cal_stud/jdn.htm">http://www.hermetic.ch/cal_stud/jdn.htm</a>
664
for instance):</p>
665
<pre class="verbatim"><ol><li>    <span class="i">$  perl</span> -<span class="w">MTime::JulianDay</span> -<a class="l_k" href="functions/le.html">le</a> <span class="q">&#39;print local_julian_day( time )&#39;</span></li><li>    <span class="n">55608</span></li></ol></pre><a name="How-do-I-find-yesterday's-date%3f"></a><h2>How do I find yesterday's date?
666 667 668
    
   
</h2>
669
<p>(contributed by brian d foy)</p>
670 671
<p>To do it correctly, you can use one of the <code class="inline"><span class="w">Date</span></code>
 modules since they
672
work with calendars instead of times. The <a href="http://search.cpan.org/perldoc/DateTime">DateTime</a> module makes it
673 674
simple, and give you the same time of day, only the day before,
despite daylight saving time changes:</p>
675
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">DateTime</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$yesterday</span> = <span class="w">DateTime</span><span class="w">-&gt;now</span><span class="w">-&gt;subtract</span><span class="s">(</span> <span class="w">days</span> <span class="cm">=&gt;</span> <span class="n">1</span> <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;Yesterday was $yesterday\n&quot;</span><span class="sc">;</span></li></ol></pre><p>You can also use the <a href="http://search.cpan.org/perldoc/Date::Calc">Date::Calc</a> module using its <code class="inline"><span class="w">Today_and_Now</span></code>
676

677
function.</p>
678 679
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Date::Calc</span> <span class="q">qw( Today_and_Now Add_Delta_DHMS )</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@date_time</span> = <span class="i">Add_Delta_DHMS</span><span class="s">(</span> <span class="i">Today_and_Now</span><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="n">-1</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span> <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;@date_time\n&quot;</span><span class="sc">;</span></li></ol></pre><p>Most people try to use the time rather than the calendar to figure out
dates, but that assumes that days are twenty-four hours each. For
680
most people, there are two days a year when they aren't: the switch to
681
and from summer time throws this off. For example, the rest of the
682
suggestions will be wrong sometimes:</p>
683 684
<p>Starting with Perl 5.10, <a href="Time/Piece.html">Time::Piece</a> and <a href="Time/Seconds.html">Time::Seconds</a> are part
of the standard distribution, so you might think that you could do
685
something like this:</p>
686 687
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Time::Piece</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Time::Seconds</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$yesterday</span> = <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span> - <span class="w">ONE_DAY</span><span class="sc">;</span> <span class="c"># WRONG</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;Yesterday was $yesterday\n&quot;</span><span class="sc">;</span></li></ol></pre><p>The <a href="Time/Piece.html">Time::Piece</a> module exports a new <code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code> that returns an
object, and <a href="Time/Seconds.html">Time::Seconds</a> exports the <code class="inline"><span class="w">ONE_DAY</span></code>
688 689 690 691 692
 constant that is a
set number of seconds. This means that it always gives the time 24
hours ago, which is not always yesterday. This can cause problems
around the end of daylight saving time when there's one day that is 25
hours long.</p>
693
<p>You have the same problem with <a href="Time/Local.html">Time::Local</a>, which will give the wrong
694
answer for those same special cases:</p>
695
<pre class="verbatim"><ol><li>    <span class="c"># contributed by Gunnar Hjalmarsson</span></li><li>     <a class="l_k" href="functions/use.html">use</a> <span class="w">Time::Local</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="i">$today</span> = <span class="w">timelocal</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">12</span><span class="cm">,</span> <span class="s">(</span> <a class="l_k" href="functions/localtime.html">localtime</a> <span class="s">)</span>[<span class="n">3</span>..<span class="n">5</span>]<span class="sc">;</span></li><li>     <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$d</span><span class="cm">,</span> <span class="i">$m</span><span class="cm">,</span> <span class="i">$y</span><span class="s">)</span> = <span class="s">(</span> <a class="l_k" href="functions/localtime.html">localtime</a> <span class="i">$today</span>-<span class="n">86400</span> <span class="s">)</span>[<span class="n">3</span>..<span class="n">5</span>]<span class="sc">;</span> <span class="c"># WRONG</span></li><li>     <a class="l_k" href="functions/printf.html">printf</a> <span class="q">&quot;Yesterday: %d-%02d-%02d\n&quot;</span><span class="cm">,</span> <span class="i">$y</span>+<span class="n">1900</span><span class="cm">,</span> <span class="i">$m</span>+<span class="n">1</span><span class="cm">,</span> <span class="i">$d</span><span class="sc">;</span></li></ol></pre><a name="Does-Perl-have-a-Year-2000-or-2038-problem%3f-Is-Perl-Y2K-compliant%3f"></a><h2>Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?</h2>
696 697 698 699 700 701 702 703
<p>(contributed by brian d foy)</p>
<p>Perl itself never had a Y2K problem, although that never stopped people
from creating Y2K problems on their own. See the documentation for
<code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code> for its proper use.</p>
<p>Starting with Perl 5.12, <code class="inline"><a class="l_k" href="functions/localtime.html">localtime</a></code> and <code class="inline"><a class="l_k" href="functions/gmtime.html">gmtime</a></code> can handle dates past
03:14:08 January 19, 2038, when a 32-bit based time would overflow. You
still might get a warning on a 32-bit <code class="inline"><span class="w">perl</span></code>
:</p>
704
<pre class="verbatim"><ol><li>    <span class="i">% perl5</span>.<span class="n">12</span> -<span class="w">E</span> <span class="q">&#39;say scalar localtime( 0x9FFF_FFFFFFFF )&#39;</span></li><li>    <span class="w">Integer</span> <span class="w">overflow</span> <span class="w">in</span> <span class="w">hexadecimal</span> <span class="w">number</span> <span class="w">at</span> -e <span class="w">line</span> <span class="n">1.</span></li><li>    <span class="w">Wed</span> <span class="w">Nov</span>  <span class="n">1</span> <span class="n">19</span><span class="co">:</span><span class="n">42</span><span class="co">:</span><span class="n">39</span> <span class="n">5576711</span></li></ol></pre><p>On a 64-bit <code class="inline"><span class="w">perl</span></code>
705 706
, you can get even larger dates for those really long
running projects:</p>
707
<pre class="verbatim"><ol><li>    <span class="i">% perl5</span>.<span class="n">12</span> -<span class="w">E</span> <span class="q">&#39;say scalar gmtime( 0x9FFF_FFFFFFFF )&#39;</span></li><li>    <span class="w">Thu</span> <span class="w">Nov</span>  <span class="n">2</span> <span class="n">00</span><span class="co">:</span><span class="n">42</span><span class="co">:</span><span class="n">39</span> <span class="n">5576711</span></li></ol></pre><p>You're still out of luck if you need to keep track of decaying protons
708
though.</p>
709 710 711 712 713
<a name="Data%3a-Strings"></a><h1>Data: Strings</h1>
<a name="How-do-I-validate-input%3f"></a><h2>How do I validate input?</h2>
<p>(contributed by brian d foy)</p>
<p>There are many ways to ensure that values are what you expect or
want to accept. Besides the specific examples that we cover in the
714
perlfaq, you can also look at the modules with "Assert" and "Validate"
715
in their names, along with other modules such as <a href="http://search.cpan.org/perldoc/Regexp::Common">Regexp::Common</a>.</p>
716
<p>Some modules have validation for particular types of input, such
717 718
as <a href="http://search.cpan.org/perldoc/Business::ISBN">Business::ISBN</a>, <a href="http://search.cpan.org/perldoc/Business::CreditCard">Business::CreditCard</a>, <a href="http://search.cpan.org/perldoc/Email::Valid">Email::Valid</a>,
and <a href="http://search.cpan.org/perldoc/Data::Validate::IP">Data::Validate::IP</a>.</p>
719
<a name="How-do-I-unescape-a-string%3f"></a><h2>How do I unescape a string?</h2>
720 721
<p>It depends just what you mean by "escape". URL escapes are dealt
with in <a href="perlfaq9.html">perlfaq9</a>. Shell escapes with the backslash (<code class="inline">\</code>
722 723
)
character are removed with</p>
724
<pre class="verbatim"><ol><li>    <span class="q">s/\\(.)/$1/g</span><span class="sc">;</span></li></ol></pre><p>This won't expand <code class="inline"><span class="q">&quot;\n&quot;</span></code>
725 726 727 728 729 730 731
 or <code class="inline"><span class="q">&quot;\t&quot;</span></code>
 or any other special escapes.</p>
<a name="How-do-I-remove-consecutive-pairs-of-characters%3f"></a><h2>How do I remove consecutive pairs of characters?</h2>
<p>(contributed by brian d foy)</p>
<p>You can use the substitution operator to find pairs of characters (or
runs of characters) and replace them with a single instance. In this
substitution, we find a character in <code class="inline">(.)</code>. The memory parentheses
732
store the matched character in the back-reference <code class="inline">\<span class="w">g1</span></code>
733 734 735 736
 and we use
that to require that the same thing immediately follow it. We replace
that part of the string with the character in <code class="inline"><span class="i">$1</span></code>
.</p>
737
<pre class="verbatim"><ol><li>    <span class="q">s/(.)\g1/$1/g</span><span class="sc">;</span></li></ol></pre><p>We can also use the transliteration operator, <code class="inline"><a class="l_k" href="functions/tr.html">tr///</a></code>. In this
738
example, the search list side of our <code class="inline"><a class="l_k" href="functions/tr.html">tr///</a></code> contains nothing, but
739
the <code class="inline"><span class="w">c</span></code>
740 741
 option complements that so it contains everything. The
replacement list also contains nothing, so the transliteration is
742
almost a no-op since it won't do any replacements (or more exactly,
743 744 745
replace the character with itself). However, the <code class="inline"><a class="l_k" href="functions/s.html">s</a></code> option squashes
duplicated and consecutive characters in the string so a character
does not show up next to itself</p>
746
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$str</span> = <span class="q">&#39;Haarlem&#39;</span><span class="sc">;</span>   <span class="c"># in the Netherlands</span></li><li>    <span class="i">$str</span> =~ <span class="q">tr///cs</span><span class="sc">;</span>       <span class="c"># Now Harlem, like in New York</span></li></ol></pre><a name="How-do-I-expand-function-calls-in-a-string%3f"></a><h2>How do I expand function calls in a string?</h2>
747
<p>(contributed by brian d foy)</p>
748
<p>This is documented in <a href="perlref.html">perlref</a>, and although it's not the easiest
749 750
thing to read, it does work. In each of these examples, we call the
function inside the braces used to dereference a reference. If we
751
have more than one return value, we can construct and dereference an
752
anonymous array. In this case, we call the function in list context.</p>
753
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The time values are @{ [localtime] }.\n&quot;</span><span class="sc">;</span></li></ol></pre><p>If we want to call the function in scalar context, we have to do a bit
754 755
more work. We can really have any code we like inside the braces, so
we simply have to end with the scalar reference, although how you do
756 757 758
that is up to you, and you can use code inside the braces. Note that
the use of parens creates a list context, so we need <code class="inline"><a class="l_k" href="functions/scalar.html">scalar</a></code> to
force the scalar context on the function:</p>
759
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The time is ${\(scalar localtime)}.\n&quot;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The time is ${ my $x = localtime; \$x }.\n&quot;</span><span class="sc">;</span></li></ol></pre><p>If your function already returns a reference, you don't need to create
760
the reference yourself.</p>
761
<pre class="verbatim"><ol><li><a name="timestamp"></a>    sub <span class="m">timestamp</span> <span class="s">{</span> <a class="l_k" href="functions/my.html">my</a> <span class="i">$t</span> = <a class="l_k" href="functions/localtime.html">localtime</a><span class="sc">;</span> \<span class="i">$t</span> <span class="s">}</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The time is ${ timestamp() }.\n&quot;</span><span class="sc">;</span></li></ol></pre><p>The <code class="inline"><span class="w">Interpolation</span></code>
762
 module can also do a lot of magic for you. You can
763
specify a variable name, in this case <code class="inline"><span class="w">E</span></code>
764 765 766
, to set up a tied hash that
does the interpolation for you. It has several other methods to do this
as well.</p>
767
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Interpolation</span> <span class="w">E</span> <span class="cm">=&gt;</span> <span class="q">&#39;eval&#39;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The time values are $E{localtime()}.\n&quot;</span><span class="sc">;</span></li></ol></pre><p>In most cases, it is probably easier to simply use string concatenation,
768
which also forces scalar context.</p>
769 770
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;The time is &quot;</span> . <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="s">)</span> . <span class="q">&quot;.\n&quot;</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-find-matching%2fnesting-anything%3f"></a><h2>How do I find matching/nesting anything?</h2>
<p>To find something between two single
771 772 773 774
characters, a pattern like <code class="inline"><span class="q">/x([^x]*)x/</span></code>
 will get the intervening
bits in $1. For multiple ones, then something more like
<code class="inline"><span class="q">/alpha(.*?)omega/</span></code>
775 776 777 778 779 780 781 782 783 784
 would be needed. For nested patterns
and/or balanced expressions, see the so-called
<a href="perlre.html#(%3fPARNO)-(%3f-PARNO)-(%3f%2bPARNO)-(%3fR)-(%3f0)">(?PARNO)</a>
construct (available since perl 5.10).
The CPAN module <a href="http://search.cpan.org/perldoc/Regexp::Common">Regexp::Common</a> can help to build such
regular expressions (see in particular
<a href="http://search.cpan.org/perldoc/Regexp::Common::balanced">Regexp::Common::balanced</a> and <a href="http://search.cpan.org/perldoc/Regexp::Common::delimited">Regexp::Common::delimited</a>).</p>
<p>More complex cases will require to write a parser, probably
using a parsing module from CPAN, like
<a href="http://search.cpan.org/perldoc/Regexp::Grammars">Regexp::Grammars</a>, <a href="http://search.cpan.org/perldoc/Parse::RecDescent">Parse::RecDescent</a>, <a href="http://search.cpan.org/perldoc/Parse::Yapp">Parse::Yapp</a>,
785
<a href="Text/Balanced.html">Text::Balanced</a>, or <a href="http://search.cpan.org/perldoc/Marpa::R2">Marpa::R2</a>.</p>
786
<a name="How-do-I-reverse-a-string%3f"></a><h2>How do I reverse a string?</h2>
787
<p>Use <code class="inline"><a class="l_k" href="functions/reverse.html">reverse()</a></code> in scalar context, as documented in
788
<a href="functions/reverse.html">reverse</a>.</p>
789
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$reversed</span> = <a class="l_k" href="functions/reverse.html">reverse</a> <span class="i">$string</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-expand-tabs-in-a-string%3f"></a><h2>How do I expand tabs in a string?</h2>
790
<p>You can do it yourself:</p>
791
<pre class="verbatim"><ol><li>    <span class="n">1</span> while <span class="i">$string</span> =~ <span class="q">s/\t+/&#39; &#39; x (length($&amp;) * 8 - length($`) % 8)/e</span><span class="sc">;</span></li></ol></pre><p>Or you can just use the <a href="Text/Tabs.html">Text::Tabs</a> module (part of the standard Perl
792
distribution).</p>
793 794 795 796 797
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Text::Tabs</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@expanded_lines</span> = <span class="i">expand</span><span class="s">(</span><span class="i">@lines_with_tabs</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-reformat-a-paragraph%3f"></a><h2>How do I reformat a paragraph?</h2>
<p>Use <a href="Text/Wrap.html">Text::Wrap</a> (part of the standard Perl distribution):</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Text::Wrap</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">wrap</span><span class="s">(</span><span class="q">&quot;\t&quot;</span><span class="cm">,</span> <span class="q">&#39;  &#39;</span><span class="cm">,</span> <span class="i">@paragraphs</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The paragraphs you give to <a href="Text/Wrap.html">Text::Wrap</a> should not contain embedded
newlines. <a href="Text/Wrap.html">Text::Wrap</a> doesn't justify the lines (flush-right).</p>
<p>Or use the CPAN module <a href="http://search.cpan.org/perldoc/Text::Autoformat">Text::Autoformat</a>. Formatting files can be
798
easily done by making a shell alias, like so:</p>
799
<pre class="verbatim"><ol><li>    <span class="w">alias</span> <span class="w">fmt</span>=<span class="q">&quot;perl -i -MText::Autoformat -n0777 \</span></li><li>        <span class="q">        -e &#39;print autoformat $_, {all=&gt;1}&#39; $*&quot;</span></li></ol></pre><p>See the documentation for <a href="http://search.cpan.org/perldoc/Text::Autoformat">Text::Autoformat</a> to appreciate its many
800 801 802 803 804
capabilities.</p>
<a name="How-can-I-access-or-change-N-characters-of-a-string%3f"></a><h2>How can I access or change N characters of a string?</h2>
<p>You can access the first characters of a string with substr().
To get the first character, for example, start at position 0
and grab the string of length 1.</p>
805
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$string</span> = <span class="q">&quot;Just another Perl Hacker&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$first_char</span> = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$string</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">1</span> <span class="s">)</span><span class="sc">;</span>  <span class="c">#  &#39;J&#39;</span></li></ol></pre><p>To change part of a string, you can use the optional fourth
806
argument which is the replacement string.</p>
807 808 809
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$string</span><span class="cm">,</span> <span class="n">13</span><span class="cm">,</span> <span class="n">4</span><span class="cm">,</span> <span class="q">&quot;Perl 5.8.0&quot;</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>You can also use substr() as an lvalue.</p>
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$string</span><span class="cm">,</span> <span class="n">13</span><span class="cm">,</span> <span class="n">4</span> <span class="s">)</span> =  <span class="q">&quot;Perl 5.8.0&quot;</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-change-the-Nth-occurrence-of-something%3f"></a><h2>How do I change the Nth occurrence of something?</h2>
<p>You have to keep track of N yourself. For example, let's say you want
810 811 812 813 814
to change the fifth occurrence of <code class="inline"><span class="q">&quot;whoever&quot;</span></code>
 or <code class="inline"><span class="q">&quot;whomever&quot;</span></code>
 into
<code class="inline"><span class="q">&quot;whosoever&quot;</span></code>
 or <code class="inline"><span class="q">&quot;whomsoever&quot;</span></code>
815
, case insensitively. These
816
all assume that $_ contains the string to be altered.</p>
817
<pre class="verbatim"><ol><li>    <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li>    <span class="q">s{((whom?)ever)}{</span></li><li>    <span class="q">    ++$count == 5       # is it the 5th?</span></li><li>        <span class="q">        ? &quot;${2}soever&quot;  # yes, swap</span></li><li>        <span class="q">        : $1            # renege and leave it there</span></li><li>        <span class="q">        }ige</span><span class="sc">;</span></li></ol></pre><p>In the more general case, you can use the <code class="inline">/g</code> modifier in a <code class="inline">while</code>
818 819

loop, keeping count of matches.</p>
820
<pre class="verbatim"><ol><li>    <span class="i">$WANT</span> = <span class="n">3</span><span class="sc">;</span></li><li>    <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li>    <span class="i">$_</span> = <span class="q">&quot;One fish two fish red fish blue fish&quot;</span><span class="sc">;</span></li><li>    while <span class="s">(</span><span class="q">/(\w+)\s+fish\b/gi</span><span class="s">)</span> <span class="s">{</span></li><li>        if <span class="s">(</span>++<span class="i">$count</span> == <span class="i">$WANT</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;The third fish is a $1 one.\n&quot;</span><span class="sc">;</span></li><li>        <span class="s">}</span></li><li>    <span class="s">}</span></li></ol></pre><p>That prints out: <code class="inline"><span class="q">&quot;The third fish is a red one.&quot;</span></code>
821 822
  You can also use a
repetition count and repeated pattern like this:</p>
823 824
<pre class="verbatim"><ol><li>    <span class="q">/(?:\w+\s+fish\s+){2}(\w+)\s+fish/i</span><span class="sc">;</span></li></ol></pre><a name="How-can-I-count-the-number-of-occurrences-of-a-substring-within-a-string%3f"></a><h2>How can I count the number of occurrences of a substring within a string?</h2>
<p>There are a number of ways, with varying efficiency. If you want a
825 826
count of a certain single character (X) within a string, you can use the
<code class="inline"><a class="l_k" href="functions/tr.html">tr///</a></code> function like so:</p>
827
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$string</span> = <span class="q">&quot;ThisXlineXhasXsomeXx&#39;sXinXit&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$count</span> = <span class="s">(</span><span class="i">$string</span> =~ <span class="q">tr/X//</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;There are $count X characters in the string&quot;</span><span class="sc">;</span></li></ol></pre><p>This is fine if you are just looking for a single character. However,
828
if you are trying to count multiple character substrings within a
829 830
larger string, <code class="inline"><a class="l_k" href="functions/tr.html">tr///</a></code> won't work. What you can do is wrap a while()
loop around a global pattern match. For example, let's count negative
831
integers:</p>
832
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$string</span> = <span class="q">&quot;-9 55 48 -2 23 -76 4 14 -44&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/while.html">while</a> <span class="s">(</span><span class="i">$string</span> =~ <span class="q">/-\d+/g</span><span class="s">)</span> <span class="s">{</span> <span class="i">$count</span>++ <span class="s">}</span></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;There are $count negative numbers in the string&quot;</span><span class="sc">;</span></li></ol></pre><p>Another version uses a global match in list context, then assigns the
833
result to a scalar, producing a count of the number of matches.</p>
834
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$count</span> = <span class="s">(</span><span class="s">)</span> = <span class="i">$string</span> =~ <span class="q">/-\d+/g</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-capitalize-all-the-words-on-one-line%3f"></a><h2>How do I capitalize all the words on one line?
835 836
   </h2>
<p>(contributed by brian d foy)</p>
837
<p>Damian Conway's <a href="http://search.cpan.org/perldoc/Text::Autoformat">Text::Autoformat</a> handles all of the thinking
838
for you.</p>
839 840
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Text::Autoformat</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$x</span> = <span class="q">&quot;Dr. Strangelove or: How I Learned to Stop &quot;</span>.</li><li>      <span class="q">&quot;Worrying and Love the Bomb&quot;</span><span class="sc">;</span></li><li></li><li>    <a class="l_k" href="functions/print.html">print</a> <span class="i">$x</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/for.html">for</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$style</span> <span class="s">(</span><span class="q">qw( sentence title highlight )</span><span class="s">)</span> <span class="s">{</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="i">autoformat</span><span class="s">(</span><span class="i">$x</span><span class="cm">,</span> <span class="s">{</span> <span class="w">case</span> <span class="cm">=&gt;</span> <span class="i">$style</span> <span class="s">}</span><span class="s">)</span><span class="cm">,</span> <span class="q">&quot;\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>How do you want to capitalize those words?</p>
<pre class="verbatim"><ol><li>    <span class="w">FRED</span> <span class="w">AND</span> <span class="w">BARNEY&#39;S</span> <span class="w">LODGE</span>        <span class="c"># all uppercase</span></li><li>    <span class="w">Fred</span> <span class="w">And</span> <span class="w">Barney&#39;s</span> <span class="w">Lodge</span>        <span class="c"># title case</span></li><li>    <span class="w">Fred</span> <a class="l_k" href="functions/and.html">and</a> <span class="w">Barney&#39;s</span> <span class="w">Lodge</span>        <span class="c"># highlight case</span></li></ol></pre><p>It's not as easy a problem as it looks. How many words do you think
841
are in there? Wait for it... wait for it.... If you answered 5
842 843
you're right. Perl words are groups of <code class="inline">\<span class="w">w</span>+</code>
, but that's not what
844 845
you want to capitalize. How is Perl supposed to know not to capitalize
that <code class="inline"><a class="l_k" href="functions/s.html">s</a></code> after the apostrophe? You could try a regular expression:</p>
846
<pre class="verbatim"><ol><li>    <span class="i">$string</span> =~ <span class="q">s/ (</span></li><li>                 <span class="q">                 (^\w)    #at the beginning of the line</span></li><li>                   <span class="q">                   |      # or</span></li><li>                 <span class="q">                 (\s\w)   #preceded by whitespace</span></li><li>                   <span class="q">                   )</span></li><li>                <span class="q">                /\U$1/xg</span><span class="sc">;</span></li><li></li><li>    <span class="i">$string</span> =~ <span class="q">s/([\w&#39;]+)/\u\L$1/g</span><span class="sc">;</span></li></ol></pre><p>Now, what if you don't want to capitalize that "and"? Just use
847
<a href="http://search.cpan.org/perldoc/Text::Autoformat">Text::Autoformat</a> and get on with the next problem. :)</p>
848
<a name="How-can-I-split-a-%5bcharacter%5d-delimited-string-except-when-inside-%5bcharacter%5d%3f"></a><h2>How can I split a [character]-delimited string except when inside [character]?</h2>
849 850
<p>Several modules can handle this sort of parsing--<a href="Text/Balanced.html">Text::Balanced</a>,
<a href="http://search.cpan.org/perldoc/Text::CSV">Text::CSV</a>, <a href="http://search.cpan.org/perldoc/Text::CSV_XS">Text::CSV_XS</a>, and <a href="Text/ParseWords.html">Text::ParseWords</a>, among others.</p>
851
<p>Take the example case of trying to split a string that is
852
comma-separated into its different fields. You can't use <code class="inline"><a class="l_k" href="functions/split.html">split(/,/)</a></code>
853
because you shouldn't split if the comma is inside quotes. For
854
example, take a data line like this:</p>
855 856 857
<pre class="verbatim"><ol><li>    <span class="w">SAR001</span><span class="cm">,</span><span class="q">&quot;&quot;</span><span class="cm">,</span><span class="q">&quot;Cimetrix, Inc&quot;</span><span class="cm">,</span><span class="q">&quot;Bob Smith&quot;</span><span class="cm">,</span><span class="q">&quot;CAM&quot;</span><span class="cm">,</span><span class="w">N</span><span class="cm">,</span><span class="n">8</span><span class="cm">,</span><span class="n">1</span><span class="cm">,</span><span class="n">0</span><span class="cm">,</span><span class="n">7</span><span class="cm">,</span><span class="q">&quot;Error, Core Dumped&quot;</span></li></ol></pre><p>Due to the restriction of the quotes, this is a fairly complex
problem. Thankfully, we have Jeffrey Friedl, author of
<i>Mastering Regular Expressions</i>, to handle these for us. He
858 859
suggests (assuming your string is contained in <code class="inline"><span class="i">$text</span></code>
):</p>
860
<pre class="verbatim"><ol><li>     <a class="l_k" href="functions/my.html">my</a> <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/push.html">push</a><span class="s">(</span><span class="i">@new</span><span class="cm">,</span> <span class="i">$+</span><span class="s">)</span> <a class="l_k" href="functions/while.html">while</a> <span class="i">$text</span> =~ <span class="q">m{</span></li><li>         <span class="q">         &quot;([^\&quot;\\]*(?:\\.[^\&quot;\\]*)*)&quot;,? # groups the phrase inside the quotes</span></li><li>        <span class="q">        | ([^,]+),?</span></li><li>        <span class="q">        | ,</span></li><li>     <span class="q">     }gx</span><span class="sc">;</span></li><li>     <a class="l_k" href="functions/push.html">push</a><span class="s">(</span><span class="i">@new</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a><span class="s">)</span> <a class="l_k" href="functions/if.html">if</a> <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span><span class="i">$text</span><span class="cm">,</span><span class="n">-1</span><span class="cm">,</span><span class="n">1</span><span class="s">)</span> <a class="l_k" href="functions/eq.html">eq</a> <span class="q">&#39;,&#39;</span><span class="sc">;</span></li></ol></pre><p>If you want to represent quotation marks inside a
861 862 863
quotation-mark-delimited field, escape them with backslashes (eg,
<code class="inline"><span class="q">&quot;like \&quot;this\&quot;&quot;</span></code>
.</p>
864
<p>Alternatively, the <a href="Text/ParseWords.html">Text::ParseWords</a> module (part of the standard
865
Perl distribution) lets you say:</p>
866 867 868 869 870
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/use.html">use</a> <span class="w">Text::ParseWords</span><span class="sc">;</span></li><li>    <span class="i">@new</span> = <span class="i">quotewords</span><span class="s">(</span><span class="q">&quot;,&quot;</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="i">$text</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>For parsing or generating CSV, though, using <a href="http://search.cpan.org/perldoc/Text::CSV">Text::CSV</a> rather than
implementing it yourself is highly recommended; you'll save yourself odd bugs
popping up later by just using code which has already been tried and tested in
production for years.</p>
<a name="How-do-I-strip-blank-space-from-the-beginning%2fend-of-a-string%3f"></a><h2>How do I strip blank space from the beginning/end of a string?</h2>
871 872 873
<p>(contributed by brian d foy)</p>
<p>A substitution can do this for you. For a single line, you want to
replace all the leading or trailing whitespace with nothing. You
874
can do that with a pair of substitutions:</p>
875
<pre class="verbatim"><ol><li>    <span class="q">s/^\s+//</span><span class="sc">;</span></li><li>    <span class="q">s/\s+$//</span><span class="sc">;</span></li></ol></pre><p>You can also write that as a single substitution, although it turns
876
out the combined statement is slower than the separate ones. That
877
might not matter to you, though:</p>
878
<pre class="verbatim"><ol><li>    <span class="q">s/^\s+|\s+$//g</span><span class="sc">;</span></li></ol></pre><p>In this regular expression, the alternation matches either at the
879 880 881 882 883
beginning or the end of the string since the anchors have a lower
precedence than the alternation. With the <code class="inline">/g</code> flag, the substitution
makes all possible matches, so it gets both. Remember, the trailing
newline matches the <code class="inline">\s+</code>, and  the <code class="inline"><span class="i">$</span></code>
 anchor can match to the
884
absolute end of the string, so the newline disappears too. Just add
885
the newline to the output, which has the added benefit of preserving
886 887
"blank" (consisting entirely of whitespace) lines which the <code class="inline">^\s+</code>
would remove all by itself:</p>
888
<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>        <span class="q">s/^\s+|\s+$//g</span><span class="sc">;</span></li><li>        <a class="l_k" href="functions/print.html">print</a> <span class="q">&quot;$_\n&quot;</span><span class="sc">;</span></li><li>    <span class="s">}</span></li></ol></pre><p>For a multi-line string, you can apply the regular expression to each
889 890
logical line in the string by adding the <code class="inline">/m</code> flag (for
"multi-line"). With the <code class="inline">/m</code> flag, the <code class="inline"><span class="i">$</span></code>
891
 matches <i>before</i> an
892 893
embedded newline, so it doesn't remove it. This pattern still removes
the newline at the end of the string:</p>
894
<pre class="verbatim"><ol><li>    <span class="i">$string</span> =~ <span class="q">s/^\s+|\s+$//gm</span><span class="sc">;</span></li></ol></pre><p>Remember that lines consisting entirely of whitespace will disappear,
895
since the first part of the alternation can match the entire string
896
and replace it with nothing. If you need to keep embedded blank lines,
897
you have to do a little more work. Instead of matching any whitespace
898
(since that includes a newline), just match the other whitespace:</p>
899
<pre class="verbatim"><ol><li>    <span class="i">$string</span> =~ <span class="q">s/^[\t\f ]+|[\t\f ]+$//mg</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-pad-a-string-with-blanks-or-pad-a-number-with-zeroes%3f"></a><h2>How do I pad a string with blanks or pad a number with zeroes?</h2>
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
<p>In the following examples, <code class="inline"><span class="i">$pad_len</span></code>
 is the length to which you wish
to pad the string, <code class="inline"><span class="i">$text</span></code>
 or <code class="inline"><span class="i">$num</span></code>
 contains the string to be padded,
and <code class="inline"><span class="i">$pad_char</span></code>
 contains the padding character. You can use a single
character string constant instead of the <code class="inline"><span class="i">$pad_char</span></code>
 variable if you
know what it is in advance. And in the same way you can use an integer in
place of <code class="inline"><span class="i">$pad_len</span></code>
 if you know the pad length in advance.</p>
<p>The simplest method uses the <code class="inline"><a class="l_k" href="functions/sprintf.html">sprintf</a></code> function. It can pad on the left
or right with blanks and on the left with zeroes and it will not
truncate the result. The <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> function can only pad strings on the
right with blanks and it will truncate the result to a maximum length of
<code class="inline"><span class="i">$pad_len</span></code>
.</p>
918 919
<pre class="verbatim"><ol><li>    <span class="c"># Left padding a string with blanks (no truncation):</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%${pad_len}s&quot;</span><span class="cm">,</span> <span class="i">$text</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%*s&quot;</span><span class="cm">,</span> <span class="i">$pad_len</span><span class="cm">,</span> <span class="i">$text</span><span class="s">)</span><span class="sc">;</span>  <span class="c"># same thing</span></li><li></li><li>    <span class="c"># Right padding a string with blanks (no truncation):</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%-${pad_len}s&quot;</span><span class="cm">,</span> <span class="i">$text</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%-*s&quot;</span><span class="cm">,</span> <span class="i">$pad_len</span><span class="cm">,</span> <span class="i">$text</span><span class="s">)</span><span class="sc">;</span> <span class="c"># same thing</span></li><li></li><li>    <span class="c"># Left padding a number with 0 (no truncation):</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%0${pad_len}d&quot;</span><span class="cm">,</span> <span class="i">$num</span><span class="s">)</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a><span class="s">(</span><span class="q">&quot;%0*d&quot;</span><span class="cm">,</span> <span class="i">$pad_len</span><span class="cm">,</span> <span class="i">$num</span><span class="s">)</span><span class="sc">;</span> <span class="c"># same thing</span></li><li></li><li>    <span class="c"># Right padding a string with blanks using pack (will truncate):</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">&quot;A$pad_len&quot;</span><span class="cm">,</span><span class="i">$text</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>If you need to pad with a character other than blank or zero you can use
one of the following methods. They all generate a pad string with the
920
<code class="inline"><span class="w">x</span></code>
921 922 923 924 925
 operator and combine that with <code class="inline"><span class="i">$text</span></code>
. These methods do
not truncate <code class="inline"><span class="i">$text</span></code>
.</p>
<p>Left and right padding with any character, creating a new string:</p>
926
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <span class="i">$pad_char</span> x <span class="s">(</span> <span class="i">$pad_len</span> - <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$text</span> <span class="s">)</span> <span class="s">)</span> . <span class="i">$text</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$padded</span> = <span class="i">$text</span> . <span class="i">$pad_char</span> x <span class="s">(</span> <span class="i">$pad_len</span> - <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$text</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Left and right padding with any character, modifying <code class="inline"><span class="i">$text</span></code>
927
 directly:</p>
928
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$text</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span> <span class="s">)</span> = <span class="i">$pad_char</span> x <span class="s">(</span> <span class="i">$pad_len</span> - <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$text</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li><li>    <span class="i">$text</span> .= <span class="i">$pad_char</span> x <span class="s">(</span> <span class="i">$pad_len</span> - <a class="l_k" href="functions/length.html">length</a><span class="s">(</span> <span class="i">$text</span> <span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-extract-selected-columns-from-a-string%3f"></a><h2>How do I extract selected columns from a string?</h2>
929
<p>(contributed by brian d foy)</p>
930
<p>If you know the columns that contain the data, you can
931
use <code class="inline"><a class="l_k" href="functions/substr.html">substr</a></code> to extract a single column.</p>
932
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$column</span> = <a class="l_k" href="functions/substr.html">substr</a><span class="s">(</span> <span class="i">$line</span><span class="cm">,</span> <span class="i">$start_column</span><span class="cm">,</span> <span class="i">$length</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>You can use <code class="inline"><a class="l_k" href="functions/split.html">split</a></code> if the columns are separated by whitespace or
933 934
some other delimiter, as long as whitespace or the delimiter cannot
appear as part of the data.</p>
935
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$line</span>    = <span class="q">&#39; fred barney   betty   &#39;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@columns</span> = <a class="l_k" href="functions/split.html">split</a> <span class="q">/\s+/</span><span class="cm">,</span> <span class="i">$line</span><span class="sc">;</span></li><li>        <span class="c"># ( &#39;&#39;, &#39;fred&#39;, &#39;barney&#39;, &#39;betty&#39; );</span></li><li></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">$line</span>    = <span class="q">&#39;fred||barney||betty&#39;</span><span class="sc">;</span></li><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@columns</span> = <a class="l_k" href="functions/split.html">split</a> <span class="q">/\|/</span><span class="cm">,</span> <span class="i">$line</span><span class="sc">;</span></li><li>        <span class="c"># ( &#39;fred&#39;, &#39;&#39;, &#39;barney&#39;, &#39;&#39;, &#39;betty&#39; );</span></li></ol></pre><p>If you want to work with comma-separated values, don't do this since
936
that format is a bit more complicated. Use one of the modules that
937 938
handle that format, such as <a href="http://search.cpan.org/perldoc/Text::CSV">Text::CSV</a>, <a href="http://search.cpan.org/perldoc/Text::CSV_XS">Text::CSV_XS</a>, or
<a href="http://search.cpan.org/perldoc/Text::CSV_PP">Text::CSV_PP</a>.</p>
939
<p>If you want to break apart an entire line of fixed columns, you can use
940
<code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> with the A (ASCII) format. By using a number after the format
941 942
specifier, you can denote the column width. See the <code class="inline"><a class="l_k" href="functions/pack.html">pack</a></code> and <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code>
entries in <a href="perlfunc.html">perlfunc</a> for more details.</p>
943
<pre class="verbatim"><ol><li>    <a class="l_k" href="functions/my.html">my</a> <span class="i">@fields</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span> <span class="i">$line</span><span class="cm">,</span> <span class="q">&quot;A8 A8 A8 A16 A4&quot;</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Note that spaces in the format argument to <code class="inline"><a class="l_k" href="functions/unpack.html">unpack</a></code> do not denote literal
944
spaces. If you have space separated data, you may want <code class="inline"><a class="l_k" href="functions/split.html">split</a></code> instead.</p>
945 946
<a name="How-do-I-find-the-soundex-value-of-a-string%3f"></a><h2>How do I find the soundex value of a string?</h2>
<p>(contributed by brian d foy)</p>
947 948 949 950
<p>You can use the <code class="inline"><span class="w">Text::Soundex</span></code>
 module. If you want to do fuzzy or close
matching, you might also try the <a href="http://search.cpan.org/perldoc/String::Approx">String::Approx</a>, and
<a href="http://search.cpan.org/perldoc/Text::Metaphone">Text::Metaphone</a>, and <a href="http://search.cpan.org/perldoc/Text::DoubleMetaphone">Text::DoubleMetaphone</a> modules.</p>