CINXE.COM

perlfaq4 - Data Manipulation - Perldoc Browser

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>perlfaq4 - Data Manipulation - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/perlfaq4"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" /> <style> body { background: #f4f4f5; color: #020202; } .navbar-dark { background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%); background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%); background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0); background-repeat: repeat-x; } .navbar-dark .navbar-nav .nav-link, .navbar-dark .navbar-nav .nav-link:focus { color: #fff } .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 } #wrapperlicious { margin: 0 auto; font: 0.9em 'Helvetica Neue', Helvetica, sans-serif; font-weight: normal; line-height: 1.5em; margin: 0; padding: 0; } #wrapperlicious h1 { font-size: 1.5em } #wrapperlicious h2 { font-size: 1.3em } #wrapperlicious h3 { font-size: 1.1em } #wrapperlicious h4 { font-size: 0.9em } #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3, #wrapperlicious h4, #wrapperlicious dt { color: #020202; margin-top: 1em; margin-bottom: 1em; position: relative; font-weight: bold; } #wrapperlicious a { color: inherit; text-decoration: underline } #wrapperlicious #toc { text-decoration: none } #wrapperlicious a:hover { color: #2a2a2a } #wrapperlicious a img { border: 0 } #wrapperlicious :not(pre) > code { color: inherit; background-color: rgba(0, 0, 0, 0.04); border-radius: 3px; font: 0.9em Consolas, Menlo, Monaco, monospace; padding: 0.3em; } #wrapperlicious dd { margin: 0; margin-left: 2em; } #wrapperlicious dt { color: #2a2a2a; font-weight: bold; margin-left: 0.9em; } #wrapperlicious p { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious li > p { margin-bottom: 0; margin-top: 0; } #wrapperlicious pre { border: 1px solid #c1c1c1; border-radius: 3px; font: 100% Consolas, Menlo, Monaco, monospace; margin-bottom: 1em; margin-top: 1em; } #wrapperlicious pre > code { display: block; background-color: #f6f6f6; font: 0.9em Consolas, Menlo, Monaco, monospace; line-height: 1.5em; text-align: left; white-space: pre; padding: 1em; } #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious ul { list-style-type: square; } #wrapperlicious ul ul { margin-bottom: 0px; margin-top: 0px; } #footer { font-size: 0.8em; padding-top: 0.5em; text-align: center; } #more { display: inline; font-size: 0.8em; } #perldocdiv { background-color: #fff; border: 1px solid #c1c1c1; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; margin-left: auto; margin-right: auto; padding: 3em; padding-top: 1em; max-width: 960px; } #moduleversion { float: right } #wrapperlicious .leading-notice { font-style: italic; padding-left: 1em; margin-top: 1em; margin-bottom: 1em; } #wrapperlicious .permalink { display: none; left: -0.75em; position: absolute; padding-right: 0.25em; text-decoration: none; } #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink, #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink, #wrapperlicious dt:hover .permalink { display: block; } </style> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-KVNWBNT5FB'); gtag('config', 'UA-50555-3'); </script> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="/">Perldoc Browser</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.12.3</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/perlfaq4">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0/perlfaq4">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.2/perlfaq4">5.38.2</a> <a class="dropdown-item" href="/5.38.1/perlfaq4">5.38.1</a> <a class="dropdown-item" href="/5.38.0/perlfaq4">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/perlfaq4">5.36.3</a> <a class="dropdown-item" href="/5.36.2/perlfaq4">5.36.2</a> <a class="dropdown-item" href="/5.36.1/perlfaq4">5.36.1</a> <a class="dropdown-item" href="/5.36.0/perlfaq4">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/perlfaq4">5.34.3</a> <a class="dropdown-item" href="/5.34.2/perlfaq4">5.34.2</a> <a class="dropdown-item" href="/5.34.1/perlfaq4">5.34.1</a> <a class="dropdown-item" href="/5.34.0/perlfaq4">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/perlfaq4">5.32.1</a> <a class="dropdown-item" href="/5.32.0/perlfaq4">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/perlfaq4">5.30.3</a> <a class="dropdown-item" href="/5.30.2/perlfaq4">5.30.2</a> <a class="dropdown-item" href="/5.30.1/perlfaq4">5.30.1</a> <a class="dropdown-item" href="/5.30.0/perlfaq4">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/perlfaq4">5.28.3</a> <a class="dropdown-item" href="/5.28.2/perlfaq4">5.28.2</a> <a class="dropdown-item" href="/5.28.1/perlfaq4">5.28.1</a> <a class="dropdown-item" href="/5.28.0/perlfaq4">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/perlfaq4">5.26.3</a> <a class="dropdown-item" href="/5.26.2/perlfaq4">5.26.2</a> <a class="dropdown-item" href="/5.26.1/perlfaq4">5.26.1</a> <a class="dropdown-item" href="/5.26.0/perlfaq4">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/perlfaq4">5.24.4</a> <a class="dropdown-item" href="/5.24.3/perlfaq4">5.24.3</a> <a class="dropdown-item" href="/5.24.2/perlfaq4">5.24.2</a> <a class="dropdown-item" href="/5.24.1/perlfaq4">5.24.1</a> <a class="dropdown-item" href="/5.24.0/perlfaq4">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/perlfaq4">5.22.4</a> <a class="dropdown-item" href="/5.22.3/perlfaq4">5.22.3</a> <a class="dropdown-item" href="/5.22.2/perlfaq4">5.22.2</a> <a class="dropdown-item" href="/5.22.1/perlfaq4">5.22.1</a> <a class="dropdown-item" href="/5.22.0/perlfaq4">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/perlfaq4">5.20.3</a> <a class="dropdown-item" href="/5.20.2/perlfaq4">5.20.2</a> <a class="dropdown-item" href="/5.20.1/perlfaq4">5.20.1</a> <a class="dropdown-item" href="/5.20.0/perlfaq4">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/perlfaq4">5.18.4</a> <a class="dropdown-item" href="/5.18.3/perlfaq4">5.18.3</a> <a class="dropdown-item" href="/5.18.2/perlfaq4">5.18.2</a> <a class="dropdown-item" href="/5.18.1/perlfaq4">5.18.1</a> <a class="dropdown-item" href="/5.18.0/perlfaq4">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/perlfaq4">5.16.3</a> <a class="dropdown-item" href="/5.16.2/perlfaq4">5.16.2</a> <a class="dropdown-item" href="/5.16.1/perlfaq4">5.16.1</a> <a class="dropdown-item" href="/5.16.0/perlfaq4">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/perlfaq4">5.14.4</a> <a class="dropdown-item" href="/5.14.3/perlfaq4">5.14.3</a> <a class="dropdown-item" href="/5.14.2/perlfaq4">5.14.2</a> <a class="dropdown-item" href="/5.14.1/perlfaq4">5.14.1</a> <a class="dropdown-item" href="/5.14.0/perlfaq4">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/perlfaq4">5.12.5</a> <a class="dropdown-item" href="/5.12.4/perlfaq4">5.12.4</a> <a class="dropdown-item active" href="/5.12.3/perlfaq4">5.12.3</a> <a class="dropdown-item" href="/5.12.2/perlfaq4">5.12.2</a> <a class="dropdown-item" href="/5.12.1/perlfaq4">5.12.1</a> <a class="dropdown-item" href="/5.12.0/perlfaq4">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/perlfaq4">5.10.1</a> <a class="dropdown-item" href="/5.10.0/perlfaq4">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/perlfaq4">5.8.9</a> <a class="dropdown-item" href="/5.8.8/perlfaq4">5.8.8</a> <a class="dropdown-item" href="/5.8.7/perlfaq4">5.8.7</a> <a class="dropdown-item" href="/5.8.6/perlfaq4">5.8.6</a> <a class="dropdown-item" href="/5.8.5/perlfaq4">5.8.5</a> <a class="dropdown-item" href="/5.8.4/perlfaq4">5.8.4</a> <a class="dropdown-item" href="/5.8.3/perlfaq4">5.8.3</a> <a class="dropdown-item" href="/5.8.2/perlfaq4">5.8.2</a> <a class="dropdown-item" href="/5.8.1/perlfaq4">5.8.1</a> <a class="dropdown-item" href="/5.8.0/perlfaq4">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/perlfaq4">5.6.2</a> <a class="dropdown-item" href="/5.6.1/perlfaq4">5.6.1</a> <a class="dropdown-item" href="/5.6.0/perlfaq4">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/perlfaq4">5.005_04</a> <a class="dropdown-item" href="/5.005_03/perlfaq4">5.005_03</a> <a class="dropdown-item" href="/5.005_02/perlfaq4">5.005_02</a> <a class="dropdown-item" href="/5.005_01/perlfaq4">5.005_01</a> <a class="dropdown-item" href="/5.005/perlfaq4">5.005</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-dev"> <a class="dropdown-item" href="/blead/perlfaq4">blead</a> <a class="dropdown-item" href="/5.41.6/perlfaq4">5.41.6</a> <a class="dropdown-item" href="/5.41.5/perlfaq4">5.41.5</a> <a class="dropdown-item" href="/5.41.4/perlfaq4">5.41.4</a> <a class="dropdown-item" href="/5.41.3/perlfaq4">5.41.3</a> <a class="dropdown-item" href="/5.41.2/perlfaq4">5.41.2</a> <a class="dropdown-item" href="/5.41.1/perlfaq4">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0-RC2/perlfaq4">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/perlfaq4">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/perlfaq4">5.39.10</a> <a class="dropdown-item" href="/5.39.9/perlfaq4">5.39.9</a> <a class="dropdown-item" href="/5.39.8/perlfaq4">5.39.8</a> <a class="dropdown-item" href="/5.39.7/perlfaq4">5.39.7</a> <a class="dropdown-item" href="/5.39.6/perlfaq4">5.39.6</a> <a class="dropdown-item" href="/5.39.5/perlfaq4">5.39.5</a> <a class="dropdown-item" href="/5.39.4/perlfaq4">5.39.4</a> <a class="dropdown-item" href="/5.39.3/perlfaq4">5.39.3</a> <a class="dropdown-item" href="/5.39.2/perlfaq4">5.39.2</a> <a class="dropdown-item" href="/5.39.1/perlfaq4">5.39.1</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-nav"> <a class="dropdown-item" href="/5.12.3/perl">Perl</a> <a class="dropdown-item" href="/5.12.3/perlintro">Intro</a> <a class="dropdown-item" href="/5.12.3/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/5.12.3/perlfaq">FAQs</a> <a class="dropdown-item" href="/5.12.3/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.3/perlop">Operators</a> <a class="dropdown-item" href="/5.12.3/functions">Functions</a> <a class="dropdown-item" href="/5.12.3/variables">Variables</a> <a class="dropdown-item" href="/5.12.3/modules">Modules</a> <a class="dropdown-item" href="/5.12.3/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.3/perldelta">Release Notes</a> <a class="dropdown-item" href="/5.12.3/perlcommunity">Community</a> <a class="dropdown-item" href="/5.12.3/perlhist">History</a> </div> </li> </ul> <ul class="navbar-nav"> <script> function set_expand (expand) { var perldocdiv = document.getElementById('perldocdiv'); var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width'); var expanded = (width == '' || width == 'none') ? true : false; if (expand === null) { expand = !expanded; } if ((expand && !expanded) || (!expand && expanded)) { perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px'); var button_classlist = document.getElementById('content-expand-button').classList; if (expand) { button_classlist.add('btn-light'); button_classlist.remove('btn-outline-light'); } else { button_classlist.add('btn-outline-light'); button_classlist.remove('btn-light'); } } return expand; } function toggle_expand () { var expand = set_expand(null); document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC'; } function read_expand () { return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { if (read_expand()) { set_expand(true); } }); } else if (read_expand()) { set_expand(true); } </script> <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-4" onclick="toggle_expand()">Expand</button> </ul> <form class="form-inline" method="get" action="/5.12.3/search"> <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search" value=""> </form> </div> </nav> <div id="wrapperlicious" class="container-fluid"> <div id="perldocdiv"> <div id="links"> <a href="/5.12.3/perlfaq4">perlfaq4</a> <div id="more"> (<a href="/5.12.3/perlfaq4.txt">source</a>, <a href="https://metacpan.org/pod/perlfaq4">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl 5.12.3. <a href="/perlfaq4">View the latest version</a> </div> <h1><a id="toc">CONTENTS</a></h1> <ul> <li> <a class="text-decoration-none" href="#NAME">NAME</a> </li> <li> <a class="text-decoration-none" href="#DESCRIPTION">DESCRIPTION</a> </li> <li> <a class="text-decoration-none" href="#Data:-Numbers">Data: Numbers</a> <ul> <li> <a class="text-decoration-none" href="#Why-am-I-getting-long-decimals-(eg,-19.9499999999999)-instead-of-the-numbers-I-should-be-getting-(eg,-19.95)?">Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</a> </li> <li> <a class="text-decoration-none" href="#Why-is-int()-broken?">Why is int() broken?</a> </li> <li> <a class="text-decoration-none" href="#Why-isn&#39;t-my-octal-data-interpreted-correctly?">Why isn&#39;t my octal data interpreted correctly?</a> </li> <li> <a class="text-decoration-none" href="#Does-Perl-have-a-round()-function?-What-about-ceil()-and-floor()?-Trig-functions?">Does Perl have a round() function? What about ceil() and floor()? Trig functions?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-convert-between-numeric-representations/bases/radixes?">How do I convert between numeric representations/bases/radixes?</a> </li> <li> <a class="text-decoration-none" href="#Why-doesn&#39;t-&amp;-work-the-way-I-want-it-to?">Why doesn&#39;t &amp; work the way I want it to?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-multiply-matrices?">How do I multiply matrices?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-perform-an-operation-on-a-series-of-integers?">How do I perform an operation on a series of integers?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-output-Roman-numerals?">How can I output Roman numerals?</a> </li> <li> <a class="text-decoration-none" href="#Why-aren&#39;t-my-random-numbers-random?">Why aren&#39;t my random numbers random?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-get-a-random-number-between-X-and-Y?">How do I get a random number between X and Y?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Data:-Dates">Data: Dates</a> <ul> <li> <a class="text-decoration-none" href="#How-do-I-find-the-day-or-week-of-the-year?">How do I find the day or week of the year?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-find-the-current-century-or-millennium?">How do I find the current century or millennium?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-compare-two-dates-and-find-the-difference?">How can I compare two dates and find the difference?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-take-a-string-and-turn-it-into-epoch-seconds?">How can I take a string and turn it into epoch seconds?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-find-the-Julian-Day?">How can I find the Julian Day?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-find-yesterday&#39;s-date?">How do I find yesterday&#39;s date? </a> </li> <li> <a class="text-decoration-none" href="#Does-Perl-have-a-Year-2000-or-2038-problem?-Is-Perl-Y2K-compliant?">Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Data:-Strings">Data: Strings</a> <ul> <li> <a class="text-decoration-none" href="#How-do-I-validate-input?">How do I validate input?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-unescape-a-string?">How do I unescape a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-remove-consecutive-pairs-of-characters?">How do I remove consecutive pairs of characters?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-expand-function-calls-in-a-string?">How do I expand function calls in a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-find-matching/nesting-anything?">How do I find matching/nesting anything?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-reverse-a-string?">How do I reverse a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-expand-tabs-in-a-string?">How do I expand tabs in a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-reformat-a-paragraph?">How do I reformat a paragraph?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-access-or-change-N-characters-of-a-string?">How can I access or change N characters of a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-change-the-Nth-occurrence-of-something?">How do I change the Nth occurrence of something?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-count-the-number-of-occurrences-of-a-substring-within-a-string?">How can I count the number of occurrences of a substring within a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-capitalize-all-the-words-on-one-line?">How do I capitalize all the words on one line? </a> </li> <li> <a class="text-decoration-none" href="#How-can-I-split-a-%5Bcharacter%5D-delimited-string-except-when-inside-%5Bcharacter%5D?">How can I split a [character] delimited string except when inside [character]?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-strip-blank-space-from-the-beginning/end-of-a-string?">How do I strip blank space from the beginning/end of a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-pad-a-string-with-blanks-or-pad-a-number-with-zeroes?">How do I pad a string with blanks or pad a number with zeroes?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-extract-selected-columns-from-a-string?">How do I extract selected columns from a string?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-find-the-soundex-value-of-a-string?">How do I find the soundex value of a string?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-expand-variables-in-text-strings?">How can I expand variables in text strings?</a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-wrong-with-always-quoting-%22$vars%22?">What&#39;s wrong with always quoting &quot;$vars&quot;?</a> </li> <li> <a class="text-decoration-none" href="#Why-don&#39;t-my-%3C%3CHERE-documents-work?">Why don&#39;t my &lt;&lt;HERE documents work?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Data:-Arrays">Data: Arrays</a> <ul> <li> <a class="text-decoration-none" href="#What-is-the-difference-between-a-list-and-an-array?">What is the difference between a list and an array?</a> </li> <li> <a class="text-decoration-none" href="#What-is-the-difference-between-$array%5B1%5D-and-@array%5B1%5D?">What is the difference between $array[1] and @array[1]?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-remove-duplicate-elements-from-a-list-or-array?">How can I remove duplicate elements from a list or array?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-tell-whether-a-certain-element-is-contained-in-a-list-or-array?">How can I tell whether a certain element is contained in a list or array?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-compute-the-difference-of-two-arrays?-How-do-I-compute-the-intersection-of-two-arrays?">How do I compute the difference of two arrays? How do I compute the intersection of two arrays?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-test-whether-two-arrays-or-hashes-are-equal?">How do I test whether two arrays or hashes are equal?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-find-the-first-array-element-for-which-a-condition-is-true?">How do I find the first array element for which a condition is true?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-handle-linked-lists?">How do I handle linked lists?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-handle-circular-lists?">How do I handle circular lists? </a> </li> <li> <a class="text-decoration-none" href="#How-do-I-shuffle-an-array-randomly?">How do I shuffle an array randomly?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-process/modify-each-element-of-an-array?">How do I process/modify each element of an array?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-select-a-random-element-from-an-array?">How do I select a random element from an array?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-permute-N-elements-of-a-list?">How do I permute N elements of a list? </a> </li> <li> <a class="text-decoration-none" href="#How-do-I-sort-an-array-by-(anything)?">How do I sort an array by (anything)?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-manipulate-arrays-of-bits?">How do I manipulate arrays of bits?</a> </li> <li> <a class="text-decoration-none" href="#Why-does-defined()-return-true-on-empty-arrays-and-hashes?">Why does defined() return true on empty arrays and hashes?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Data:-Hashes-(Associative-Arrays)">Data: Hashes (Associative Arrays)</a> <ul> <li> <a class="text-decoration-none" href="#How-do-I-process-an-entire-hash?">How do I process an entire hash?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-merge-two-hashes?">How do I merge two hashes? </a> </li> <li> <a class="text-decoration-none" href="#What-happens-if-I-add-or-remove-keys-from-a-hash-while-iterating-over-it?">What happens if I add or remove keys from a hash while iterating over it?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-look-up-a-hash-element-by-value?">How do I look up a hash element by value?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-know-how-many-entries-are-in-a-hash?">How can I know how many entries are in a hash?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-sort-a-hash-(optionally-by-value-instead-of-key)?">How do I sort a hash (optionally by value instead of key)?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-always-keep-my-hash-sorted?">How can I always keep my hash sorted? </a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-the-difference-between-%22delete%22-and-%22undef%22-with-hashes?">What&#39;s the difference between &quot;delete&quot; and &quot;undef&quot; with hashes?</a> </li> <li> <a class="text-decoration-none" href="#Why-don&#39;t-my-tied-hashes-make-the-defined/exists-distinction?">Why don&#39;t my tied hashes make the defined/exists distinction?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-reset-an-each()-operation-part-way-through?">How do I reset an each() operation part-way through?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-get-the-unique-keys-from-two-hashes?">How can I get the unique keys from two hashes?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-store-a-multidimensional-array-in-a-DBM-file?">How can I store a multidimensional array in a DBM file?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-make-my-hash-remember-the-order-I-put-elements-into-it?">How can I make my hash remember the order I put elements into it?</a> </li> <li> <a class="text-decoration-none" href="#Why-does-passing-a-subroutine-an-undefined-element-in-a-hash-create-it?">Why does passing a subroutine an undefined element in a hash create it?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-make-the-Perl-equivalent-of-a-C-structure/C++-class/hash-or-array-of-hashes-or-arrays?">How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-use-a-reference-as-a-hash-key?">How can I use a reference as a hash key?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Data:-Misc">Data: Misc</a> <ul> <li> <a class="text-decoration-none" href="#How-do-I-handle-binary-data-correctly?">How do I handle binary data correctly?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-determine-whether-a-scalar-is-a-number/whole/integer/float?">How do I determine whether a scalar is a number/whole/integer/float?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-keep-persistent-data-across-program-calls?">How do I keep persistent data across program calls?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-print-out-or-copy-a-recursive-data-structure?">How do I print out or copy a recursive data structure?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-define-methods-for-every-class/object?">How do I define methods for every class/object?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-verify-a-credit-card-checksum?">How do I verify a credit card checksum?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-pack-arrays-of-doubles-or-floats-for-XS-code?">How do I pack arrays of doubles or floats for XS code?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a> </li> </ul> <h1 id="NAME"><a class="permalink" href="#NAME">#</a>NAME</h1> <p>perlfaq4 - Data Manipulation</p> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>This section of the FAQ answers questions related to manipulating numbers, dates, strings, arrays, hashes, and miscellaneous data issues.</p> <h1 id="Data:-Numbers"><a class="permalink" href="#Data:-Numbers">#</a><a id="Data"></a>Data: Numbers</h1> <h2 id="Why-am-I-getting-long-decimals-(eg,-19.9499999999999)-instead-of-the-numbers-I-should-be-getting-(eg,-19.95)?"><a class="permalink" href="#Why-am-I-getting-long-decimals-(eg,-19.9499999999999)-instead-of-the-numbers-I-should-be-getting-(eg,-19.95)?">#</a><a id="Why"></a><a id="Why-am-I-getting-long-decimals-eg-19.9499999999999-instead-of-the-numbers-I-should-be-getting-eg-19.95"></a>Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</h2> <p>For the long explanation, see David Goldberg&#39;s &quot;What Every Computer Scientist Should Know About Floating-Point Arithmetic&quot; (http://docs.sun.com/source/806-3568/ncg_goldberg.html).</p> <p>Internally, your computer represents floating-point numbers in binary. Digital (as in powers of two) computers cannot store all numbers exactly. Some real numbers lose precision in the process. This is a problem with how computers store numbers and affects all computer languages, not just Perl.</p> <p><a href="/5.12.3/perlnumber">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 <code>printf</code> or <code>sprintf</code> function. See the <a href="/5.12.3/perlop">&quot;Floating Point Arithmetic&quot;</a> for more details.</p> <pre><code>printf &quot;%.2f&quot;, 10/3; my $number = sprintf &quot;%.2f&quot;, 10/3;</code></pre> <h2 id="Why-is-int()-broken?"><a class="permalink" href="#Why-is-int()-broken?">#</a><a id="Why1"></a><a id="Why-is-int-broken"></a>Why is int() broken?</h2> <p>Your <code>int()</code> is most probably working just fine. It&#39;s the numbers that aren&#39;t quite what you think.</p> <p>First, see the answer to &quot;Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?&quot;.</p> <p>For example, this</p> <pre><code>print int(0.6/0.2-2), &quot;\n&quot;;</code></pre> <p>will in most computers print 0, not 1, because even such simple numbers as 0.6 and 0.2 cannot be presented exactly by floating-point numbers. What you think in the above as &#39;three&#39; is really more like 2.9999999999999995559.</p> <h2 id="Why-isn&#39;t-my-octal-data-interpreted-correctly?"><a class="permalink" href="#Why-isn&#39;t-my-octal-data-interpreted-correctly?">#</a><a id="Why2"></a><a id="Why-isnt-my-octal-data-interpreted-correctly"></a>Why isn&#39;t my octal data interpreted correctly?</h2> <p>(contributed by brian d foy)</p> <p>You&#39;re probably trying to convert a string to a number, which Perl only 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> <pre><code>my $string = &#39;0644&#39;; print $string + 0; # prints 644 print $string + 44; # prints 688, certainly not octal!</code></pre> <p>This problem usually involves one of the Perl built-ins that has the same name a Unix command that uses octal numbers as arguments on the command line. In this example, <code>chmod</code> on the command line knows that its first argument is octal because that&#39;s what it does:</p> <pre><code>%prompt&gt; chmod 644 file</code></pre> <p>If you want to use the same literal digits (644) in Perl, you have to tell Perl to treat them as octal numbers either by prefixing the digits with a <code>0</code> or using <code>oct</code>:</p> <pre><code>chmod( 0644, $file); # right, has leading zero chmod( oct(644), $file ); # also correct</code></pre> <p>The problem comes in when you take your numbers from something that Perl thinks is a string, such as a command line argument in <code>@ARGV</code>:</p> <pre><code>chmod( $ARGV[0], $file); # wrong, even if &quot;0644&quot; chmod( oct($ARGV[0]), $file ); # correct, treat string as octal</code></pre> <p>You can always check the value you&#39;re using by printing it in octal notation to ensure it matches what you think it should be. Print it in octal and decimal format:</p> <pre><code>printf &quot;0%o %d&quot;, $number, $number;</code></pre> <h2 id="Does-Perl-have-a-round()-function?-What-about-ceil()-and-floor()?-Trig-functions?"><a class="permalink" href="#Does-Perl-have-a-round()-function?-What-about-ceil()-and-floor()?-Trig-functions?">#</a><a id="Does"></a><a id="Does-Perl-have-a-round-function-What-about-ceil-and-floor-Trig-functions"></a>Does Perl have a round() function? What about ceil() and floor()? Trig functions?</h2> <p>Remember that <code>int()</code> merely truncates toward 0. For rounding to a certain number of digits, <code>sprintf()</code> or <code>printf()</code> is usually the easiest route.</p> <pre><code>printf(&quot;%.3f&quot;, 3.1415926535); # prints 3.142</code></pre> <p>The <code>POSIX</code> module (part of the standard Perl distribution) implements <code>ceil()</code>, <code>floor()</code>, and a number of other mathematical and trigonometric functions.</p> <pre><code>use POSIX; $ceil = ceil(3.5); # 4 $floor = floor(3.5); # 3</code></pre> <p>In 5.000 to 5.003 perls, trigonometry was done in the <code>Math::Complex</code> module. With 5.004, the <code>Math::Trig</code> module (part of the standard Perl distribution) implements the trigonometric functions. Internally it uses the <code>Math::Complex</code> module and some functions can break out from 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 the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.</p> <p>To see why, notice how you&#39;ll still have an issue on half-way-point alternation:</p> <pre><code>for ($i = 0; $i &lt; 1.01; $i += 0.05) { printf &quot;%.1f &quot;,$i} 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0</code></pre> <p>Don&#39;t blame Perl. It&#39;s the same as in C. IEEE says we have to do this. Perl numbers whose absolute values are integers under 2**31 (on 32 bit machines) will work pretty much like mathematical integers. Other numbers are not guaranteed.</p> <h2 id="How-do-I-convert-between-numeric-representations/bases/radixes?"><a class="permalink" href="#How-do-I-convert-between-numeric-representations/bases/radixes?">#</a><a id="How"></a><a id="How-do-I-convert-between-numeric-representations-bases-radixes"></a>How do I convert between numeric representations/bases/radixes?</h2> <p>As always with Perl there is more than one way to do it. Below are a few examples of approaches to making common conversions between number representations. This is intended to be representational rather than exhaustive.</p> <p>Some of the examples later in <a href="/5.12.3/perlfaq4">perlfaq4</a> use the <code>Bit::Vector</code> module from CPAN. The reason you might choose <code>Bit::Vector</code> over the perl built in functions is that it works with numbers of ANY size, that it is optimized for speed on some operations, and for at least some programmers the notation might be familiar.</p> <dl> <dt id="How-do-I-convert-hexadecimal-into-decimal"><a class="permalink" href="#How-do-I-convert-hexadecimal-into-decimal">#</a><a id="How1"></a>How do I convert hexadecimal into decimal</dt> <dd> <p>Using perl&#39;s built in conversion of <code>0x</code> notation:</p> <pre><code>$dec = 0xDEADBEEF;</code></pre> <p>Using the <code>hex</code> function:</p> <pre><code>$dec = hex(&quot;DEADBEEF&quot;);</code></pre> <p>Using <code>pack</code>:</p> <pre><code>$dec = unpack(&quot;N&quot;, pack(&quot;H8&quot;, substr(&quot;0&quot; x 8 . &quot;DEADBEEF&quot;, -8)));</code></pre> <p>Using the CPAN module <code>Bit::Vector</code>:</p> <pre><code>use Bit::Vector; $vec = Bit::Vector-&gt;new_Hex(32, &quot;DEADBEEF&quot;); $dec = $vec-&gt;to_Dec();</code></pre> </dd> <dt id="How-do-I-convert-from-decimal-to-hexadecimal"><a class="permalink" href="#How-do-I-convert-from-decimal-to-hexadecimal">#</a><a id="How2"></a>How do I convert from decimal to hexadecimal</dt> <dd> <p>Using <code>sprintf</code>:</p> <pre><code>$hex = sprintf(&quot;%X&quot;, 3735928559); # upper case A-F $hex = sprintf(&quot;%x&quot;, 3735928559); # lower case a-f</code></pre> <p>Using <code>unpack</code>:</p> <pre><code>$hex = unpack(&quot;H*&quot;, pack(&quot;N&quot;, 3735928559));</code></pre> <p>Using <code>Bit::Vector</code>:</p> <pre><code>use Bit::Vector; $vec = Bit::Vector-&gt;new_Dec(32, -559038737); $hex = $vec-&gt;to_Hex();</code></pre> <p>And <code>Bit::Vector</code> supports odd bit counts:</p> <pre><code>use Bit::Vector; $vec = Bit::Vector-&gt;new_Dec(33, 3735928559); $vec-&gt;Resize(32); # suppress leading 0 if unwanted $hex = $vec-&gt;to_Hex();</code></pre> </dd> <dt id="How-do-I-convert-from-octal-to-decimal"><a class="permalink" href="#How-do-I-convert-from-octal-to-decimal">#</a><a id="How3"></a>How do I convert from octal to decimal</dt> <dd> <p>Using Perl&#39;s built in conversion of numbers with leading zeros:</p> <pre><code>$dec = 033653337357; # note the leading 0!</code></pre> <p>Using the <code>oct</code> function:</p> <pre><code>$dec = oct(&quot;33653337357&quot;);</code></pre> <p>Using <code>Bit::Vector</code>:</p> <pre><code>use Bit::Vector; $vec = Bit::Vector-&gt;new(32); $vec-&gt;Chunk_List_Store(3, split(//, reverse &quot;33653337357&quot;)); $dec = $vec-&gt;to_Dec();</code></pre> </dd> <dt id="How-do-I-convert-from-decimal-to-octal"><a class="permalink" href="#How-do-I-convert-from-decimal-to-octal">#</a><a id="How4"></a>How do I convert from decimal to octal</dt> <dd> <p>Using <code>sprintf</code>:</p> <pre><code>$oct = sprintf(&quot;%o&quot;, 3735928559);</code></pre> <p>Using <code>Bit::Vector</code>:</p> <pre><code>use Bit::Vector; $vec = Bit::Vector-&gt;new_Dec(32, -559038737); $oct = reverse join(&#39;&#39;, $vec-&gt;Chunk_List_Read(3));</code></pre> </dd> <dt id="How-do-I-convert-from-binary-to-decimal"><a class="permalink" href="#How-do-I-convert-from-binary-to-decimal">#</a><a id="How5"></a>How do I convert from binary to decimal</dt> <dd> <p>Perl 5.6 lets you write binary numbers directly with the <code>0b</code> notation:</p> <pre><code>$number = 0b10110110;</code></pre> <p>Using <code>oct</code>:</p> <pre><code>my $input = &quot;10110110&quot;; $decimal = oct( &quot;0b$input&quot; );</code></pre> <p>Using <code>pack</code> and <code>ord</code>:</p> <pre><code>$decimal = ord(pack(&#39;B8&#39;, &#39;10110110&#39;));</code></pre> <p>Using <code>pack</code> and <code>unpack</code> for larger strings:</p> <pre><code>$int = unpack(&quot;N&quot;, pack(&quot;B32&quot;, substr(&quot;0&quot; x 32 . &quot;11110101011011011111011101111&quot;, -32))); $dec = sprintf(&quot;%d&quot;, $int); # substr() is used to left pad a 32 character string with zeros.</code></pre> <p>Using <code>Bit::Vector</code>:</p> <pre><code>$vec = Bit::Vector-&gt;new_Bin(32, &quot;11011110101011011011111011101111&quot;); $dec = $vec-&gt;to_Dec();</code></pre> </dd> <dt id="How-do-I-convert-from-decimal-to-binary"><a class="permalink" href="#How-do-I-convert-from-decimal-to-binary">#</a><a id="How6"></a>How do I convert from decimal to binary</dt> <dd> <p>Using <code>sprintf</code> (perl 5.6+):</p> <pre><code>$bin = sprintf(&quot;%b&quot;, 3735928559);</code></pre> <p>Using <code>unpack</code>:</p> <pre><code>$bin = unpack(&quot;B*&quot;, pack(&quot;N&quot;, 3735928559));</code></pre> <p>Using <code>Bit::Vector</code>:</p> <pre><code>use Bit::Vector; $vec = Bit::Vector-&gt;new_Dec(32, -559038737); $bin = $vec-&gt;to_Bin();</code></pre> <p>The remaining transformations (e.g. hex -&gt; oct, bin -&gt; hex, etc.) are left as an exercise to the inclined reader.</p> </dd> </dl> <h2 id="Why-doesn&#39;t-&amp;-work-the-way-I-want-it-to?"><a class="permalink" href="#Why-doesn&#39;t-&amp;-work-the-way-I-want-it-to?">#</a><a id="Why3"></a><a id="Why-doesnt-work-the-way-I-want-it-to"></a>Why doesn&#39;t &amp; work the way I want it to?</h2> <p>The behavior of binary arithmetic operators depends on whether they&#39;re used on numbers or strings. The operators treat a string as a series of bits and work with that (the string <code>&quot;3&quot;</code> is the bit pattern <code>00110011</code>). The operators work with the binary form of a number (the number <code>3</code> is treated as the bit pattern <code>00000011</code>).</p> <p>So, saying <code>11 &amp; 3</code> performs the &quot;and&quot; operation on numbers (yielding <code>3</code>). Saying <code>&quot;11&quot; &amp; &quot;3&quot;</code> performs the &quot;and&quot; operation on strings (yielding <code>&quot;1&quot;</code>).</p> <p>Most problems with <code>&amp;</code> and <code>|</code> arise because the programmer thinks they have a number but really it&#39;s a string. The rest arise because the programmer says:</p> <pre><code>if (&quot;\020\020&quot; &amp; &quot;\101\101&quot;) { # ... }</code></pre> <p>but a string consisting of two null bytes (the result of <code>&quot;\020\020&quot; &amp; &quot;\101\101&quot;</code>) is not a false value in Perl. You need:</p> <pre><code>if ( (&quot;\020\020&quot; &amp; &quot;\101\101&quot;) !~ /[^\000]/) { # ... }</code></pre> <h2 id="How-do-I-multiply-matrices?"><a class="permalink" href="#How-do-I-multiply-matrices?">#</a><a id="How7"></a><a id="How-do-I-multiply-matrices"></a>How do I multiply matrices?</h2> <p>Use the <code>Math::Matrix</code> or <code>Math::MatrixReal</code> modules (available from CPAN) or the <code>PDL</code> extension (also available from CPAN).</p> <h2 id="How-do-I-perform-an-operation-on-a-series-of-integers?"><a class="permalink" href="#How-do-I-perform-an-operation-on-a-series-of-integers?">#</a><a id="How8"></a><a id="How-do-I-perform-an-operation-on-a-series-of-integers"></a>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> <pre><code>@results = map { my_func($_) } @array;</code></pre> <p>For example:</p> <pre><code>@triple = map { 3 * $_ } @single;</code></pre> <p>To call a function on each element of an array, but ignore the results:</p> <pre><code>foreach $iterator (@array) { some_func($iterator); }</code></pre> <p>To call a function on each integer in a (small) range, you <b>can</b> use:</p> <pre><code>@results = map { some_func($_) } (5 .. 25);</code></pre> <p>but you should be aware that the <code>..</code> operator creates an array of all integers in the range. This can take a lot of memory for large ranges. Instead use:</p> <pre><code>@results = (); for ($i=5; $i &lt; 500_005; $i++) { push(@results, some_func($i)); }</code></pre> <p>This situation has been fixed in Perl5.005. Use of <code>..</code> in a <code>for</code> loop will iterate over the range, without creating the entire range.</p> <pre><code>for my $i (5 .. 500_005) { push(@results, some_func($i)); }</code></pre> <p>will not create a list of 500,000 integers.</p> <h2 id="How-can-I-output-Roman-numerals?"><a class="permalink" href="#How-can-I-output-Roman-numerals?">#</a><a id="How9"></a><a id="How-can-I-output-Roman-numerals"></a>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> <h2 id="Why-aren&#39;t-my-random-numbers-random?"><a class="permalink" href="#Why-aren&#39;t-my-random-numbers-random?">#</a><a id="Why4"></a><a id="Why-arent-my-random-numbers-random"></a>Why aren&#39;t my random numbers random?</h2> <p>If you&#39;re using a version of Perl before 5.004, you must call <code>srand</code> once at the start of your program to seed the random number generator.</p> <pre><code class="plaintext">BEGIN { srand() if $] &lt; 5.004 }</code></pre> <p>5.004 and later automatically call <code>srand</code> at the beginning. Don&#39;t call <code>srand</code> more than once--you make your numbers less random, rather than more.</p> <p>Computers are good at being predictable and bad at being random (despite appearances caused by bugs in your programs :-). see the <i>random</i> article in the &quot;Far More Than You Ever Wanted To Know&quot; collection in <a href="http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz">http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</a>, courtesy of Tom Phoenix, talks more about this. John von Neumann said, &quot;Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin.&quot;</p> <p>If you want numbers that are more random than <code>rand</code> with <code>srand</code> provides, you should also check out the <code>Math::TrulyRandom</code> module from CPAN. It uses the imperfections in your system&#39;s timer to generate random numbers, but this takes quite a while. If you want a better pseudorandom generator than comes with your operating system, look at &quot;Numerical Recipes in C&quot; at <a href="http://www.nr.com/">http://www.nr.com/</a>.</p> <h2 id="How-do-I-get-a-random-number-between-X-and-Y?"><a class="permalink" href="#How-do-I-get-a-random-number-between-X-and-Y?">#</a><a id="How10"></a><a id="How-do-I-get-a-random-number-between-X-and-Y"></a>How do I get a random number between X and Y?</h2> <p>To get a random number between two values, you can use the <code>rand()</code> built-in to get a random number between 0 and 1. From there, you shift that into the range that you want.</p> <p><code>rand($x)</code> returns a number such that <code>0 &lt;= rand($x) &lt; $x</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> <pre><code>my $number = 10 + int rand( 15-10+1 ); # ( 10,11,12,13,14, or 15 )</code></pre> <p>Hence you derive the following simple function to abstract that. It selects a random integer between the two given integers (inclusive), For example: <code>random_int_between(50,120)</code>.</p> <pre><code>sub random_int_between { my($min, $max) = @_; # Assumes that the two arguments are integers themselves! return $min if $min == $max; ($min, $max) = ($max, $min) if $min &gt; $max; return $min + int rand(1 + $max - $min); }</code></pre> <h1 id="Data:-Dates"><a class="permalink" href="#Data:-Dates">#</a><a id="Data1"></a>Data: Dates</h1> <h2 id="How-do-I-find-the-day-or-week-of-the-year?"><a class="permalink" href="#How-do-I-find-the-day-or-week-of-the-year?">#</a><a id="How11"></a><a id="How-do-I-find-the-day-or-week-of-the-year"></a>How do I find the day or week of the year?</h2> <p>The <code>localtime</code> function returns the day of the year. Without an argument <code>localtime</code> uses the current time.</p> <pre><code>$day_of_year = (localtime)[7];</code></pre> <p>The <code>POSIX</code> module can also format a date as the day of the year or week of the year.</p> <pre><code>use POSIX qw/strftime/; my $day_of_year = strftime &quot;%j&quot;, localtime; my $week_of_year = strftime &quot;%W&quot;, localtime;</code></pre> <p>To get the day of year for any date, use <code>POSIX</code>&#39;s <code>mktime</code> to get a time in epoch seconds for the argument to <code>localtime</code>.</p> <pre><code>use POSIX qw/mktime strftime/; my $week_of_year = strftime &quot;%W&quot;, localtime( mktime( 0, 0, 0, 18, 11, 87 ) );</code></pre> <p>The <code>Date::Calc</code> module provides two functions to calculate these.</p> <pre><code>use Date::Calc; my $day_of_year = Day_of_Year( 1987, 12, 18 ); my $week_of_year = Week_of_Year( 1987, 12, 18 );</code></pre> <h2 id="How-do-I-find-the-current-century-or-millennium?"><a class="permalink" href="#How-do-I-find-the-current-century-or-millennium?">#</a><a id="How12"></a><a id="How-do-I-find-the-current-century-or-millennium"></a>How do I find the current century or millennium?</h2> <p>Use the following simple functions:</p> <pre><code>sub get_century { return int((((localtime(shift || time))[5] + 1999))/100); } sub get_millennium { return 1+int((((localtime(shift || time))[5] + 1899))/1000); }</code></pre> <p>On some systems, the <code>POSIX</code> module&#39;s <code>strftime()</code> function has been extended in a non-standard way to use a <code>%C</code> format, which they sometimes claim is the &quot;century&quot;. It isn&#39;t, because on most such systems, this is only the first two digits of the four-digit year, and thus cannot be used to reliably determine the current century or millennium.</p> <h2 id="How-can-I-compare-two-dates-and-find-the-difference?"><a class="permalink" href="#How-can-I-compare-two-dates-and-find-the-difference?">#</a><a id="How13"></a><a id="How-can-I-compare-two-dates-and-find-the-difference"></a>How can I compare two dates and find the difference?</h2> <p>(contributed by brian d foy)</p> <p>You could just store all your dates as a number and then subtract. Life isn&#39;t always that simple though. If you want to work with formatted dates, the <code>Date::Manip</code>, <code>Date::Calc</code>, or <code>DateTime</code> modules can help you.</p> <h2 id="How-can-I-take-a-string-and-turn-it-into-epoch-seconds?"><a class="permalink" href="#How-can-I-take-a-string-and-turn-it-into-epoch-seconds?">#</a><a id="How14"></a><a id="How-can-I-take-a-string-and-turn-it-into-epoch-seconds"></a>How can I take a string and turn it into epoch seconds?</h2> <p>If it&#39;s a regular enough string that it always has the same format, you can split it up and pass the parts to <code>timelocal</code> in the standard <code>Time::Local</code> module. Otherwise, you should look into the <code>Date::Calc</code> and <code>Date::Manip</code> modules from CPAN.</p> <h2 id="How-can-I-find-the-Julian-Day?"><a class="permalink" href="#How-can-I-find-the-Julian-Day?">#</a><a id="How15"></a><a id="How-can-I-find-the-Julian-Day"></a>How can I find the Julian Day?</h2> <p>(contributed by brian d foy and Dave Cross)</p> <p>You can use the <code>Time::JulianDay</code> module available on CPAN. Ensure that you really want to find a Julian day, though, as many people have different ideas about Julian days. See http://www.hermetic.ch/cal_stud/jdn.htm for instance.</p> <p>You can also try the <code>DateTime</code> module, which can convert a date/time to a Julian Day.</p> <pre><code>$ perl -MDateTime -le&#39;print DateTime-&gt;today-&gt;jd&#39; 2453401.5</code></pre> <p>Or the modified Julian Day</p> <pre><code>$ perl -MDateTime -le&#39;print DateTime-&gt;today-&gt;mjd&#39; 53401</code></pre> <p>Or even the day of the year (which is what some people think of as a Julian day)</p> <pre><code>$ perl -MDateTime -le&#39;print DateTime-&gt;today-&gt;doy&#39; 31</code></pre> <h2 id="How-do-I-find-yesterday&#39;s-date?"><a class="permalink" href="#How-do-I-find-yesterday&#39;s-date?">#</a><a id="How16"></a><a id="How-do-I-find-yesterdays-date"></a>How do I find yesterday&#39;s date? </h2> <p>(contributed by brian d foy)</p> <p>Use one of the Date modules. The <code>DateTime</code> module makes it simple, and give you the same time of day, only the day before.</p> <pre><code>use DateTime; my $yesterday = DateTime-&gt;now-&gt;subtract( days =&gt; 1 ); print &quot;Yesterday was $yesterday\n&quot;;</code></pre> <p>You can also use the <code>Date::Calc</code> module using its <code>Today_and_Now</code> function.</p> <pre><code>use Date::Calc qw( Today_and_Now Add_Delta_DHMS ); my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 ); print &quot;@date_time\n&quot;;</code></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 most people, there are two days a year when they aren&#39;t: the switch to and from summer time throws this off. Let the modules do the work.</p> <p>If you absolutely must do it yourself (or can&#39;t use one of the modules), here&#39;s a solution using <code>Time::Local</code>, which comes with Perl:</p> <pre><code># contributed by Gunnar Hjalmarsson use Time::Local; my $today = timelocal 0, 0, 12, ( localtime )[3..5]; my ($d, $m, $y) = ( localtime $today-86400 )[3..5]; printf &quot;Yesterday: %d-%02d-%02d\n&quot;, $y+1900, $m+1, $d;</code></pre> <p>In this case, you measure the day starting at noon, and subtract 24 hours. Even if the length of the calendar day is 23 or 25 hours, you&#39;ll still end up on the previous calendar day, although not at noon. Since you don&#39;t care about the time, the one hour difference doesn&#39;t matter and you end up with the previous date.</p> <h2 id="Does-Perl-have-a-Year-2000-or-2038-problem?-Is-Perl-Y2K-compliant?"><a class="permalink" href="#Does-Perl-have-a-Year-2000-or-2038-problem?-Is-Perl-Y2K-compliant?">#</a><a id="Does1"></a><a id="Does-Perl-have-a-Year-2000-or-2038-problem-Is-Perl-Y2K-compliant"></a>Does Perl have a Year 2000 or 2038 problem? Is Perl Y2K compliant?</h2> <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>localtime</code> for its proper use.</p> <p>Starting with Perl 5.11, <code>localtime</code> and <code>gmtime</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>perl</code>:</p> <pre><code class="plaintext">% perl5.11.2 -E &#39;say scalar localtime( 0x9FFF_FFFFFFFF )&#39; Integer overflow in hexadecimal number at -e line 1. Wed Nov 1 19:42:39 5576711</code></pre> <p>On a 64-bit <code>perl</code>, you can get even larger dates for those really long running projects:</p> <pre><code class="plaintext">% perl5.11.2 -E &#39;say scalar gmtime( 0x9FFF_FFFFFFFF )&#39; Thu Nov 2 00:42:39 5576711</code></pre> <p>You&#39;re still out of luck if you need to keep tracking of decaying protons though.</p> <h1 id="Data:-Strings"><a class="permalink" href="#Data:-Strings">#</a><a id="Data2"></a>Data: Strings</h1> <h2 id="How-do-I-validate-input?"><a class="permalink" href="#How-do-I-validate-input?">#</a><a id="How17"></a><a id="How-do-I-validate-input"></a>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 perlfaq, you can also look at the modules with &quot;Assert&quot; and &quot;Validate&quot; in their names, along with other modules such as <code>Regexp::Common</code>.</p> <p>Some modules have validation for particular types of input, such as <code>Business::ISBN</code>, <code>Business::CreditCard</code>, <code>Email::Valid</code>, and <code>Data::Validate::IP</code>.</p> <h2 id="How-do-I-unescape-a-string?"><a class="permalink" href="#How-do-I-unescape-a-string?">#</a><a id="How18"></a><a id="How-do-I-unescape-a-string"></a>How do I unescape a string?</h2> <p>It depends just what you mean by &quot;escape&quot;. URL escapes are dealt with in <a href="/5.12.3/perlfaq9">perlfaq9</a>. Shell escapes with the backslash (<code>\</code>) character are removed with</p> <pre><code>s/\\(.)/$1/g;</code></pre> <p>This won&#39;t expand <code>&quot;\n&quot;</code> or <code>&quot;\t&quot;</code> or any other special escapes.</p> <h2 id="How-do-I-remove-consecutive-pairs-of-characters?"><a class="permalink" href="#How-do-I-remove-consecutive-pairs-of-characters?">#</a><a id="How19"></a><a id="How-do-I-remove-consecutive-pairs-of-characters"></a>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>(.)</code>. The memory parentheses store the matched character in the back-reference <code>\1</code> 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>$1</code>.</p> <pre><code>s/(.)\1/$1/g;</code></pre> <p>We can also use the transliteration operator, <code>tr///</code>. In this example, the search list side of our <code>tr///</code> contains nothing, but the <code>c</code> option complements that so it contains everything. The replacement list also contains nothing, so the transliteration is almost a no-op since it won&#39;t do any replacements (or more exactly, replace the character with itself). However, the <code>s</code> option squashes duplicated and consecutive characters in the string so a character does not show up next to itself</p> <pre><code>my $str = &#39;Haarlem&#39;; # in the Netherlands $str =~ tr///cs; # Now Harlem, like in New York</code></pre> <h2 id="How-do-I-expand-function-calls-in-a-string?"><a class="permalink" href="#How-do-I-expand-function-calls-in-a-string?">#</a><a id="How20"></a><a id="How-do-I-expand-function-calls-in-a-string"></a>How do I expand function calls in a string?</h2> <p>(contributed by brian d foy)</p> <p>This is documented in <a href="/5.12.3/perlref">perlref</a>, and although it&#39;s not the easiest 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 have more than one return value, we can construct and dereference an anonymous array. In this case, we call the function in list context.</p> <pre><code>print &quot;The time values are @{ [localtime] }.\n&quot;;</code></pre> <p>If we want to call the function in scalar context, we have to do a bit 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 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>scalar</code> to force the scalar context on the function:</p> <pre><code>print &quot;The time is ${\(scalar localtime)}.\n&quot; print &quot;The time is ${ my $x = localtime; \$x }.\n&quot;;</code></pre> <p>If your function already returns a reference, you don&#39;t need to create the reference yourself.</p> <pre><code>sub timestamp { my $t = localtime; \$t } print &quot;The time is ${ timestamp() }.\n&quot;;</code></pre> <p>The <code>Interpolation</code> module can also do a lot of magic for you. You can specify a variable name, in this case <code>E</code>, to set up a tied hash that does the interpolation for you. It has several other methods to do this as well.</p> <pre><code>use Interpolation E =&gt; &#39;eval&#39;; print &quot;The time values are $E{localtime()}.\n&quot;;</code></pre> <p>In most cases, it is probably easier to simply use string concatenation, which also forces scalar context.</p> <pre><code>print &quot;The time is &quot; . localtime() . &quot;.\n&quot;;</code></pre> <h2 id="How-do-I-find-matching/nesting-anything?"><a class="permalink" href="#How-do-I-find-matching/nesting-anything?">#</a><a id="How21"></a><a id="How-do-I-find-matching-nesting-anything"></a>How do I find matching/nesting anything?</h2> <p>This isn&#39;t something that can be done in one regular expression, no matter how complicated. To find something between two single characters, a pattern like <code>/x([^x]*)x/</code> will get the intervening bits in $1. For multiple ones, then something more like <code>/alpha(.*?)omega/</code> would be needed. But none of these deals with nested patterns. For balanced expressions using <code>(</code>, <code>{</code>, <code>[</code> or <code>&lt;</code> as delimiters, use the CPAN module Regexp::Common, or see <a href="/5.12.3/perlre#(%3F%3F%7B-code-%7D)">&quot;(??{ code })&quot; in perlre</a>. For other cases, you&#39;ll have to write a parser.</p> <p>If you are serious about writing a parser, there are a number of modules or oddities that will make your life a lot easier. There are the CPAN modules <code>Parse::RecDescent</code>, <code>Parse::Yapp</code>, and <code>Text::Balanced</code>; and the <code>byacc</code> program. Starting from perl 5.8 the <code>Text::Balanced</code> is part of the standard distribution.</p> <p>One simple destructive, inside-out approach that you might try is to pull out the smallest nesting parts one at a time:</p> <pre><code>while (s/BEGIN((?:(?!BEGIN)(?!END).)*)END//gs) { # do something with $1 }</code></pre> <p>A more complicated and sneaky approach is to make Perl&#39;s regular expression engine do it for you. This is courtesy Dean Inada, and rather has the nature of an Obfuscated Perl Contest entry, but it really does work:</p> <pre><code># $_ contains the string to parse # BEGIN and END are the opening and closing markers for the # nested text. @( = (&#39;(&#39;,&#39;&#39;); @) = (&#39;)&#39;,&#39;&#39;); ($re=$_)=~s/((BEGIN)|(END)|.)/$)[!$3]\Q$1\E$([!$2]/gs; @$ = (eval{/$re/},$@!~/unmatched/i); print join(&quot;\n&quot;,@$[0..$#$]) if( $$[-1] );</code></pre> <h2 id="How-do-I-reverse-a-string?"><a class="permalink" href="#How-do-I-reverse-a-string?">#</a><a id="How22"></a><a id="How-do-I-reverse-a-string"></a>How do I reverse a string?</h2> <p>Use <code>reverse()</code> in scalar context, as documented in <a href="/5.12.3/perlfunc#reverse">&quot;reverse&quot; in perlfunc</a>.</p> <pre><code>$reversed = reverse $string;</code></pre> <h2 id="How-do-I-expand-tabs-in-a-string?"><a class="permalink" href="#How-do-I-expand-tabs-in-a-string?">#</a><a id="How23"></a><a id="How-do-I-expand-tabs-in-a-string"></a>How do I expand tabs in a string?</h2> <p>You can do it yourself:</p> <pre><code>1 while $string =~ s/\t+/&#39; &#39; x (length($&amp;) * 8 - length($`) % 8)/e;</code></pre> <p>Or you can just use the <code>Text::Tabs</code> module (part of the standard Perl distribution).</p> <pre><code>use Text::Tabs; @expanded_lines = expand(@lines_with_tabs);</code></pre> <h2 id="How-do-I-reformat-a-paragraph?"><a class="permalink" href="#How-do-I-reformat-a-paragraph?">#</a><a id="How24"></a><a id="How-do-I-reformat-a-paragraph"></a>How do I reformat a paragraph?</h2> <p>Use <code>Text::Wrap</code> (part of the standard Perl distribution):</p> <pre><code>use Text::Wrap; print wrap(&quot;\t&quot;, &#39; &#39;, @paragraphs);</code></pre> <p>The paragraphs you give to <code>Text::Wrap</code> should not contain embedded newlines. <code>Text::Wrap</code> doesn&#39;t justify the lines (flush-right).</p> <p>Or use the CPAN module <code>Text::Autoformat</code>. Formatting files can be easily done by making a shell alias, like so:</p> <pre><code>alias fmt=&quot;perl -i -MText::Autoformat -n0777 \ -e &#39;print autoformat $_, {all=&gt;1}&#39; $*&quot;</code></pre> <p>See the documentation for <code>Text::Autoformat</code> to appreciate its many capabilities.</p> <h2 id="How-can-I-access-or-change-N-characters-of-a-string?"><a class="permalink" href="#How-can-I-access-or-change-N-characters-of-a-string?">#</a><a id="How25"></a><a id="How-can-I-access-or-change-N-characters-of-a-string"></a>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> <pre><code>$string = &quot;Just another Perl Hacker&quot;; $first_char = substr( $string, 0, 1 ); # &#39;J&#39;</code></pre> <p>To change part of a string, you can use the optional fourth argument which is the replacement string.</p> <pre><code>substr( $string, 13, 4, &quot;Perl 5.8.0&quot; );</code></pre> <p>You can also use substr() as an lvalue.</p> <pre><code>substr( $string, 13, 4 ) = &quot;Perl 5.8.0&quot;;</code></pre> <h2 id="How-do-I-change-the-Nth-occurrence-of-something?"><a class="permalink" href="#How-do-I-change-the-Nth-occurrence-of-something?">#</a><a id="How26"></a><a id="How-do-I-change-the-Nth-occurrence-of-something"></a>How do I change the Nth occurrence of something?</h2> <p>You have to keep track of N yourself. For example, let&#39;s say you want to change the fifth occurrence of <code>&quot;whoever&quot;</code> or <code>&quot;whomever&quot;</code> into <code>&quot;whosoever&quot;</code> or <code>&quot;whomsoever&quot;</code>, case insensitively. These all assume that $_ contains the string to be altered.</p> <pre><code>$count = 0; s{((whom?)ever)}{ ++$count == 5 # is it the 5th? ? &quot;${2}soever&quot; # yes, swap : $1 # renege and leave it there }ige;</code></pre> <p>In the more general case, you can use the <code>/g</code> modifier in a <code>while</code> loop, keeping count of matches.</p> <pre><code>$WANT = 3; $count = 0; $_ = &quot;One fish two fish red fish blue fish&quot;; while (/(\w+)\s+fish\b/gi) { if (++$count == $WANT) { print &quot;The third fish is a $1 one.\n&quot;; } }</code></pre> <p>That prints out: <code>&quot;The third fish is a red one.&quot;</code> You can also use a repetition count and repeated pattern like this:</p> <pre><code>/(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;</code></pre> <h2 id="How-can-I-count-the-number-of-occurrences-of-a-substring-within-a-string?"><a class="permalink" href="#How-can-I-count-the-number-of-occurrences-of-a-substring-within-a-string?">#</a><a id="How27"></a><a id="How-can-I-count-the-number-of-occurrences-of-a-substring-within-a-string"></a>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 count of a certain single character (X) within a string, you can use the <code>tr///</code> function like so:</p> <pre><code>$string = &quot;ThisXlineXhasXsomeXx&#39;sXinXit&quot;; $count = ($string =~ tr/X//); print &quot;There are $count X characters in the string&quot;;</code></pre> <p>This is fine if you are just looking for a single character. However, if you are trying to count multiple character substrings within a larger string, <code>tr///</code> won&#39;t work. What you can do is wrap a while() loop around a global pattern match. For example, let&#39;s count negative integers:</p> <pre><code>$string = &quot;-9 55 48 -2 23 -76 4 14 -44&quot;; while ($string =~ /-\d+/g) { $count++ } print &quot;There are $count negative numbers in the string&quot;;</code></pre> <p>Another version uses a global match in list context, then assigns the result to a scalar, producing a count of the number of matches.</p> <pre><code>$count = () = $string =~ /-\d+/g;</code></pre> <h2 id="How-do-I-capitalize-all-the-words-on-one-line?"><a class="permalink" href="#How-do-I-capitalize-all-the-words-on-one-line?">#</a><a id="How28"></a><a id="How-do-I-capitalize-all-the-words-on-one-line"></a>How do I capitalize all the words on one line? </h2> <p>(contributed by brian d foy)</p> <p>Damian Conway&#39;s <a href="/5.12.3/Text::Autoformat">Text::Autoformat</a> handles all of the thinking for you.</p> <pre><code>use Text::Autoformat; my $x = &quot;Dr. Strangelove or: How I Learned to Stop &quot;. &quot;Worrying and Love the Bomb&quot;; print $x, &quot;\n&quot;; for my $style (qw( sentence title highlight )) { print autoformat($x, { case =&gt; $style }), &quot;\n&quot;; }</code></pre> <p>How do you want to capitalize those words?</p> <pre><code class="plaintext">FRED AND BARNEY&#39;S LODGE # all uppercase Fred And Barney&#39;s Lodge # title case Fred and Barney&#39;s Lodge # highlight case</code></pre> <p>It&#39;s not as easy a problem as it looks. How many words do you think are in there? Wait for it... wait for it.... If you answered 5 you&#39;re right. Perl words are groups of <code>\w+</code>, but that&#39;s not what you want to capitalize. How is Perl supposed to know not to capitalize that <code>s</code> after the apostrophe? You could try a regular expression:</p> <pre><code>$string =~ s/ ( (^\w) #at the beginning of the line | # or (\s\w) #preceded by whitespace ) /\U$1/xg; $string =~ s/([\w&#39;]+)/\u\L$1/g;</code></pre> <p>Now, what if you don&#39;t want to capitalize that &quot;and&quot;? Just use <a href="/5.12.3/Text::Autoformat">Text::Autoformat</a> and get on with the next problem. :)</p> <h2 id="How-can-I-split-a-[character]-delimited-string-except-when-inside-[character]?"><a class="permalink" href="#How-can-I-split-a-%5Bcharacter%5D-delimited-string-except-when-inside-%5Bcharacter%5D?">#</a><a id="How29"></a><a id="How-can-I-split-a-character-delimited-string-except-when-inside-character"></a>How can I split a [character] delimited string except when inside [character]?</h2> <p>Several modules can handle this sort of parsing--<code>Text::Balanced</code>, <code>Text::CSV</code>, <code>Text::CSV_XS</code>, and <code>Text::ParseWords</code>, among others.</p> <p>Take the example case of trying to split a string that is comma-separated into its different fields. You can&#39;t use <code>split(/,/)</code> because you shouldn&#39;t split if the comma is inside quotes. For example, take a data line like this:</p> <pre><code class="plaintext">SAR001,&quot;&quot;,&quot;Cimetrix, Inc&quot;,&quot;Bob Smith&quot;,&quot;CAM&quot;,N,8,1,0,7,&quot;Error, Core Dumped&quot;</code></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 suggests (assuming your string is contained in <code>$text</code>):</p> <pre><code> @new = (); push(@new, $+) while $text =~ m{ &quot;([^\&quot;\\]*(?:\\.[^\&quot;\\]*)*)&quot;,? # groups the phrase inside the quotes | ([^,]+),? | , }gx; push(@new, undef) if substr($text,-1,1) eq &#39;,&#39;;</code></pre> <p>If you want to represent quotation marks inside a quotation-mark-delimited field, escape them with backslashes (eg, <code>&quot;like \&quot;this\&quot;&quot;</code>.</p> <p>Alternatively, the <code>Text::ParseWords</code> module (part of the standard Perl distribution) lets you say:</p> <pre><code>use Text::ParseWords; @new = quotewords(&quot;,&quot;, 0, $text);</code></pre> <h2 id="How-do-I-strip-blank-space-from-the-beginning/end-of-a-string?"><a class="permalink" href="#How-do-I-strip-blank-space-from-the-beginning/end-of-a-string?">#</a><a id="How30"></a><a id="How-do-I-strip-blank-space-from-the-beginning-end-of-a-string"></a>How do I strip blank space from the beginning/end of a string?</h2> <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 can do that with a pair of substitutions.</p> <pre><code>s/^\s+//; s/\s+$//;</code></pre> <p>You can also write that as a single substitution, although it turns out the combined statement is slower than the separate ones. That might not matter to you, though.</p> <pre><code>s/^\s+|\s+$//g;</code></pre> <p>In this regular expression, the alternation matches either at the beginning or the end of the string since the anchors have a lower precedence than the alternation. With the <code>/g</code> flag, the substitution makes all possible matches, so it gets both. Remember, the trailing newline matches the <code>\s+</code>, and the <code>$</code> anchor can match to the physical end of the string, so the newline disappears too. Just add the newline to the output, which has the added benefit of preserving &quot;blank&quot; (consisting entirely of whitespace) lines which the <code>^\s+</code> would remove all by itself.</p> <pre><code>while( &lt;&gt; ) { s/^\s+|\s+$//g; print &quot;$_\n&quot;; }</code></pre> <p>For a multi-line string, you can apply the regular expression to each logical line in the string by adding the <code>/m</code> flag (for &quot;multi-line&quot;). With the <code>/m</code> flag, the <code>$</code> matches <i>before</i> an embedded newline, so it doesn&#39;t remove it. It still removes the newline at the end of the string.</p> <pre><code>$string =~ s/^\s+|\s+$//gm;</code></pre> <p>Remember that lines consisting entirely of whitespace will disappear, since the first part of the alternation can match the entire string and replace it with nothing. If need to keep embedded blank lines, you have to do a little more work. Instead of matching any whitespace (since that includes a newline), just match the other whitespace.</p> <pre><code>$string =~ s/^[\t\f ]+|[\t\f ]+$//mg;</code></pre> <h2 id="How-do-I-pad-a-string-with-blanks-or-pad-a-number-with-zeroes?"><a class="permalink" href="#How-do-I-pad-a-string-with-blanks-or-pad-a-number-with-zeroes?">#</a><a id="How31"></a><a id="How-do-I-pad-a-string-with-blanks-or-pad-a-number-with-zeroes"></a>How do I pad a string with blanks or pad a number with zeroes?</h2> <p>In the following examples, <code>$pad_len</code> is the length to which you wish to pad the string, <code>$text</code> or <code>$num</code> contains the string to be padded, and <code>$pad_char</code> contains the padding character. You can use a single character string constant instead of the <code>$pad_char</code> variable if you know what it is in advance. And in the same way you can use an integer in place of <code>$pad_len</code> if you know the pad length in advance.</p> <p>The simplest method uses the <code>sprintf</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>pack</code> function can only pad strings on the right with blanks and it will truncate the result to a maximum length of <code>$pad_len</code>.</p> <pre><code># Left padding a string with blanks (no truncation): $padded = sprintf(&quot;%${pad_len}s&quot;, $text); $padded = sprintf(&quot;%*s&quot;, $pad_len, $text); # same thing # Right padding a string with blanks (no truncation): $padded = sprintf(&quot;%-${pad_len}s&quot;, $text); $padded = sprintf(&quot;%-*s&quot;, $pad_len, $text); # same thing # Left padding a number with 0 (no truncation): $padded = sprintf(&quot;%0${pad_len}d&quot;, $num); $padded = sprintf(&quot;%0*d&quot;, $pad_len, $num); # same thing # Right padding a string with blanks using pack (will truncate): $padded = pack(&quot;A$pad_len&quot;,$text);</code></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 <code>x</code> operator and combine that with <code>$text</code>. These methods do not truncate <code>$text</code>.</p> <p>Left and right padding with any character, creating a new string:</p> <pre><code>$padded = $pad_char x ( $pad_len - length( $text ) ) . $text; $padded = $text . $pad_char x ( $pad_len - length( $text ) );</code></pre> <p>Left and right padding with any character, modifying <code>$text</code> directly:</p> <pre><code>substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) ); $text .= $pad_char x ( $pad_len - length( $text ) );</code></pre> <h2 id="How-do-I-extract-selected-columns-from-a-string?"><a class="permalink" href="#How-do-I-extract-selected-columns-from-a-string?">#</a><a id="How32"></a><a id="How-do-I-extract-selected-columns-from-a-string"></a>How do I extract selected columns from a string?</h2> <p>(contributed by brian d foy)</p> <p>If you know the columns that contain the data, you can use <code>substr</code> to extract a single column.</p> <pre><code>my $column = substr( $line, $start_column, $length );</code></pre> <p>You can use <code>split</code> if the columns are separated by whitespace or some other delimiter, as long as whitespace or the delimiter cannot appear as part of the data.</p> <pre><code>my $line = &#39; fred barney betty &#39;; my @columns = split /\s+/, $line; # ( &#39;&#39;, &#39;fred&#39;, &#39;barney&#39;, &#39;betty&#39; ); my $line = &#39;fred||barney||betty&#39;; my @columns = split /\|/, $line; # ( &#39;fred&#39;, &#39;&#39;, &#39;barney&#39;, &#39;&#39;, &#39;betty&#39; );</code></pre> <p>If you want to work with comma-separated values, don&#39;t do this since that format is a bit more complicated. Use one of the modules that handle that format, such as <code>Text::CSV</code>, <code>Text::CSV_XS</code>, or <code>Text::CSV_PP</code>.</p> <p>If you want to break apart an entire line of fixed columns, you can use <code>unpack</code> with the A (ASCII) format. By using a number after the format specifier, you can denote the column width. See the <code>pack</code> and <code>unpack</code> entries in <a href="/5.12.3/perlfunc">perlfunc</a> for more details.</p> <pre><code>my @fields = unpack( $line, &quot;A8 A8 A8 A16 A4&quot; );</code></pre> <p>Note that spaces in the format argument to <code>unpack</code> do not denote literal spaces. If you have space separated data, you may want <code>split</code> instead.</p> <h2 id="How-do-I-find-the-soundex-value-of-a-string?"><a class="permalink" href="#How-do-I-find-the-soundex-value-of-a-string?">#</a><a id="How33"></a><a id="How-do-I-find-the-soundex-value-of-a-string"></a>How do I find the soundex value of a string?</h2> <p>(contributed by brian d foy)</p> <p>You can use the Text::Soundex module. If you want to do fuzzy or close matching, you might also try the <code>String::Approx</code>, and <code>Text::Metaphone</code>, and <code>Text::DoubleMetaphone</code> modules.</p> <h2 id="How-can-I-expand-variables-in-text-strings?"><a class="permalink" href="#How-can-I-expand-variables-in-text-strings?">#</a><a id="How34"></a><a id="How-can-I-expand-variables-in-text-strings"></a>How can I expand variables in text strings?</h2> <p>(contributed by brian d foy)</p> <p>If you can avoid it, don&#39;t, or if you can use a templating system, such as <code>Text::Template</code> or <code>Template</code> Toolkit, do that instead. You might even be able to get the job done with <code>sprintf</code> or <code>printf</code>:</p> <pre><code>my $string = sprintf &#39;Say hello to %s and %s&#39;, $foo, $bar;</code></pre> <p>However, for the one-off simple case where I don&#39;t want to pull out a full templating system, I&#39;ll use a string that has two Perl scalar variables in it. In this example, I want to expand <code>$foo</code> and <code>$bar</code> to their variable&#39;s values:</p> <pre><code>my $foo = &#39;Fred&#39;; my $bar = &#39;Barney&#39;; $string = &#39;Say hello to $foo and $bar&#39;;</code></pre> <p>One way I can do this involves the substitution operator and a double <code>/e</code> flag. The first <code>/e</code> evaluates <code>$1</code> on the replacement side and turns it into <code>$foo</code>. The second /e starts with <code>$foo</code> and replaces it with its value. <code>$foo</code>, then, turns into &#39;Fred&#39;, and that&#39;s finally what&#39;s left in the string:</p> <pre><code>$string =~ s/(\$\w+)/$1/eeg; # &#39;Say hello to Fred and Barney&#39;</code></pre> <p>The <code>/e</code> will also silently ignore violations of strict, replacing undefined variable names with the empty string. Since I&#39;m using the <code>/e</code> flag (twice even!), I have all of the same security problems I have with <code>eval</code> in its string form. If there&#39;s something odd in <code>$foo</code>, perhaps something like <code>@{[ system &quot;rm -rf /&quot; ]}</code>, then I could get myself in trouble.</p> <p>To get around the security problem, I could also pull the values from a hash instead of evaluating variable names. Using a single <code>/e</code>, I can check the hash to ensure the value exists, and if it doesn&#39;t, I can replace the missing value with a marker, in this case <code>???</code> to signal that I missed something:</p> <pre><code>my $string = &#39;This has $foo and $bar&#39;; my %Replacements = ( foo =&gt; &#39;Fred&#39;, ); # $string =~ s/\$(\w+)/$Replacements{$1}/g; $string =~ s/\$(\w+)/ exists $Replacements{$1} ? $Replacements{$1} : &#39;???&#39; /eg; print $string;</code></pre> <h2 id="What&#39;s-wrong-with-always-quoting-&quot;$vars&quot;?"><a class="permalink" href="#What&#39;s-wrong-with-always-quoting-%22$vars%22?">#</a><a id="What"></a><a id="Whats-wrong-with-always-quoting-vars"></a>What&#39;s wrong with always quoting &quot;$vars&quot;?</h2> <p>The problem is that those double-quotes force stringification--coercing numbers and references into strings--even when you don&#39;t want them to be strings. Think of it this way: double-quote expansion is used to produce new strings. If you already have a string, why do you need more?</p> <p>If you get used to writing odd things like these:</p> <pre><code>print &quot;$var&quot;; # BAD $new = &quot;$old&quot;; # BAD somefunc(&quot;$var&quot;); # BAD</code></pre> <p>You&#39;ll be in trouble. Those should (in 99.8% of the cases) be the simpler and more direct:</p> <pre><code>print $var; $new = $old; somefunc($var);</code></pre> <p>Otherwise, besides slowing you down, you&#39;re going to break code when the thing in the scalar is actually neither a string nor a number, but a reference:</p> <pre><code>func(\@array); sub func { my $aref = shift; my $oref = &quot;$aref&quot;; # WRONG }</code></pre> <p>You can also get into subtle problems on those few operations in Perl that actually do care about the difference between a string and a number, such as the magical <code>++</code> autoincrement operator or the syscall() function.</p> <p>Stringification also destroys arrays.</p> <pre><code>@lines = `command`; print &quot;@lines&quot;; # WRONG - extra blanks print @lines; # right</code></pre> <h2 id="Why-don&#39;t-my-&lt;&lt;HERE-documents-work?"><a class="permalink" href="#Why-don&#39;t-my-%3C%3CHERE-documents-work?">#</a><a id="Why5"></a><a id="Why-dont-my-HERE-documents-work"></a>Why don&#39;t my &lt;&lt;HERE documents work?</h2> <p>Check for these three things:</p> <dl> <dt id="There-must-be-no-space-after-the-&lt;&lt;-part."><a class="permalink" href="#There-must-be-no-space-after-the-%3C%3C-part.">#</a><a id="There"></a><a id="There-must-be-no-space-after-the-part"></a>There must be no space after the &lt;&lt; part.</dt> <dd> </dd> <dt id="There-(probably)-should-be-a-semicolon-at-the-end."><a class="permalink" href="#There-(probably)-should-be-a-semicolon-at-the-end.">#</a><a id="There1"></a><a id="There-probably-should-be-a-semicolon-at-the-end"></a>There (probably) should be a semicolon at the end.</dt> <dd> </dd> <dt id="You-can&#39;t-(easily)-have-any-space-in-front-of-the-tag."><a class="permalink" href="#You-can&#39;t-(easily)-have-any-space-in-front-of-the-tag.">#</a><a id="You"></a><a id="You-cant-easily-have-any-space-in-front-of-the-tag"></a>You can&#39;t (easily) have any space in front of the tag.</dt> <dd> </dd> </dl> <p>If you want to indent the text in the here document, you can do this:</p> <pre><code># all in one ($VAR = &lt;&lt;HERE_TARGET) =~ s/^\s+//gm; your text goes here HERE_TARGET</code></pre> <p>But the HERE_TARGET must still be flush against the margin. If you want that indented also, you&#39;ll have to quote in the indentation.</p> <pre><code>($quote = &lt;&lt;&#39; FINIS&#39;) =~ s/^\s+//gm; ...we will have peace, when you and all your works have perished--and the works of your dark master to whom you would deliver us. You are a liar, Saruman, and a corrupter of men&#39;s hearts. --Theoden in /usr/src/perl/taint.c FINIS $quote =~ s/\s+--/\n--/;</code></pre> <p>A nice general-purpose fixer-upper function for indented here documents follows. It expects to be called with a here document as its argument. It looks to see whether each line begins with a common substring, and if so, strips that substring off. Otherwise, it takes the amount of leading whitespace found on the first line and removes that much off each subsequent line.</p> <pre><code>sub fix { local $_ = shift; my ($white, $leader); # common whitespace and common leading string if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) { ($white, $leader) = ($2, quotemeta($1)); } else { ($white, $leader) = (/^(\s+)/, &#39;&#39;); } s/^\s*?$leader(?:$white)?//gm; return $_; }</code></pre> <p>This works with leading special strings, dynamically determined:</p> <pre><code>$remember_the_main = fix&lt;&lt;&#39; MAIN_INTERPRETER_LOOP&#39;; @@@ int @@@ runops() { @@@ SAVEI32(runlevel); @@@ runlevel++; @@@ while ( op = (*op-&gt;op_ppaddr)() ); @@@ TAINT_NOT; @@@ return 0; @@@ } MAIN_INTERPRETER_LOOP</code></pre> <p>Or with a fixed amount of leading whitespace, with remaining indentation correctly preserved:</p> <pre><code> $poem = fix&lt;&lt;EVER_ON_AND_ON; Now far ahead the Road has gone, And I must follow, if I can, Pursuing it with eager feet, Until it joins some larger way Where many paths and errands meet. And whither then? I cannot say. --Bilbo in /usr/src/perl/pp_ctl.c EVER_ON_AND_ON</code></pre> <h1 id="Data:-Arrays"><a class="permalink" href="#Data:-Arrays">#</a><a id="Data3"></a>Data: Arrays</h1> <h2 id="What-is-the-difference-between-a-list-and-an-array?"><a class="permalink" href="#What-is-the-difference-between-a-list-and-an-array?">#</a><a id="What1"></a><a id="What-is-the-difference-between-a-list-and-an-array"></a>What is the difference between a list and an array?</h2> <p>(contributed by brian d foy)</p> <p>A list is a fixed collection of scalars. An array is a variable that holds a variable collection of scalars. An array can supply its collection for list operations, so list operations also work on arrays:</p> <pre><code># slices ( &#39;dog&#39;, &#39;cat&#39;, &#39;bird&#39; )[2,3]; @animals[2,3]; # iteration foreach ( qw( dog cat bird ) ) { ... } foreach ( @animals ) { ... } my @three = grep { length == 3 } qw( dog cat bird ); my @three = grep { length == 3 } @animals; # supply an argument list wash_animals( qw( dog cat bird ) ); wash_animals( @animals );</code></pre> <p>Array operations, which change the scalars, reaaranges them, or adds or subtracts some scalars, only work on arrays. These can&#39;t work on a list, which is fixed. Array operations include <code>shift</code>, <code>unshift</code>, <code>push</code>, <code>pop</code>, and <code>splice</code>.</p> <p>An array can also change its length:</p> <pre><code>$#animals = 1; # truncate to two elements $#animals = 10000; # pre-extend to 10,001 elements</code></pre> <p>You can change an array element, but you can&#39;t change a list element:</p> <pre><code>$animals[0] = &#39;Rottweiler&#39;; qw( dog cat bird )[0] = &#39;Rottweiler&#39;; # syntax error! foreach ( @animals ) { s/^d/fr/; # works fine } foreach ( qw( dog cat bird ) ) { s/^d/fr/; # Error! Modification of read only value! }</code></pre> <p>However, if the list element is itself a variable, it appears that you can change a list element. However, the list element is the variable, not the data. You&#39;re not changing the list element, but something the list element refers to. The list element itself doesn&#39;t change: it&#39;s still the same variable.</p> <p>You also have to be careful about context. You can assign an array to a scalar to get the number of elements in the array. This only works for arrays, though:</p> <pre><code>my $count = @animals; # only works with arrays</code></pre> <p>If you try to do the same thing with what you think is a list, you get a quite different result. Although it looks like you have a list on the righthand side, Perl actually sees a bunch of scalars separated by a comma:</p> <pre><code>my $scalar = ( &#39;dog&#39;, &#39;cat&#39;, &#39;bird&#39; ); # $scalar gets bird</code></pre> <p>Since you&#39;re assigning to a scalar, the righthand side is in scalar context. The comma operator (yes, it&#39;s an operator!) in scalar context evaluates its lefthand side, throws away the result, and evaluates it&#39;s righthand side and returns the result. In effect, that list-lookalike assigns to <code>$scalar</code> it&#39;s rightmost value. Many people mess this up becuase they choose a list-lookalike whose last element is also the count they expect:</p> <pre><code>my $scalar = ( 1, 2, 3 ); # $scalar gets 3, accidentally</code></pre> <h2 id="What-is-the-difference-between-$array[1]-and-@array[1]?"><a class="permalink" href="#What-is-the-difference-between-$array%5B1%5D-and-@array%5B1%5D?">#</a><a id="What2"></a><a id="What-is-the-difference-between-array-1-and-array-1"></a>What is the difference between $array[1] and @array[1]?</h2> <p>(contributed by brian d foy)</p> <p>The difference is the sigil, that special character in front of the array name. The <code>$</code> sigil means &quot;exactly one item&quot;, while the <code>@</code> sigil means &quot;zero or more items&quot;. The <code>$</code> gets you a single scalar, while the <code>@</code> gets you a list.</p> <p>The confusion arises because people incorrectly assume that the sigil denotes the variable type.</p> <p>The <code>$array[1]</code> is a single-element access to the array. It&#39;s going to return the item in index 1 (or undef if there is no item there). If you intend to get exactly one element from the array, this is the form you should use.</p> <p>The <code>@array[1]</code> is an array slice, although it has only one index. You can pull out multiple elements simultaneously by specifying additional indices as a list, like <code>@array[1,4,3,0]</code>.</p> <p>Using a slice on the lefthand side of the assignment supplies list context to the righthand side. This can lead to unexpected results. For instance, if you want to read a single line from a filehandle, assigning to a scalar value is fine:</p> <pre><code>$array[1] = &lt;STDIN&gt;;</code></pre> <p>However, in list context, the line input operator returns all of the lines as a list. The first line goes into <code>@array[1]</code> and the rest of the lines mysteriously disappear:</p> <pre><code>@array[1] = &lt;STDIN&gt;; # most likely not what you want</code></pre> <p>Either the <code>use warnings</code> pragma or the <b>-w</b> flag will warn you when you use an array slice with a single index.</p> <h2 id="How-can-I-remove-duplicate-elements-from-a-list-or-array?"><a class="permalink" href="#How-can-I-remove-duplicate-elements-from-a-list-or-array?">#</a><a id="How35"></a><a id="How-can-I-remove-duplicate-elements-from-a-list-or-array"></a>How can I remove duplicate elements from a list or array?</h2> <p>(contributed by brian d foy)</p> <p>Use a hash. When you think the words &quot;unique&quot; or &quot;duplicated&quot;, think &quot;hash keys&quot;.</p> <p>If you don&#39;t care about the order of the elements, you could just create the hash then extract the keys. It&#39;s not important how you create that hash: just that you use <code>keys</code> to get the unique elements.</p> <pre><code>my %hash = map { $_, 1 } @array; # or a hash slice: @hash{ @array } = (); # or a foreach: $hash{$_} = 1 foreach ( @array ); my @unique = keys %hash;</code></pre> <p>If you want to use a module, try the <code>uniq</code> function from <code>List::MoreUtils</code>. In list context it returns the unique elements, preserving their order in the list. In scalar context, it returns the number of unique elements.</p> <pre><code>use List::MoreUtils qw(uniq); my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7 my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7</code></pre> <p>You can also go through each element and skip the ones you&#39;ve seen before. Use a hash to keep track. The first time the loop sees an element, that element has no key in <code>%Seen</code>. The <code>next</code> statement creates the key and immediately uses its value, which is <code>undef</code>, so the loop continues to the <code>push</code> and increments the value for that key. The next time the loop sees that same element, its key exists in the hash <i>and</i> the value for that key is true (since it&#39;s not 0 or <code>undef</code>), so the next skips that iteration and the loop goes to the next element.</p> <pre><code>my @unique = (); my %seen = (); foreach my $elem ( @array ) { next if $seen{ $elem }++; push @unique, $elem; }</code></pre> <p>You can write this more briefly using a grep, which does the same thing.</p> <pre><code>my %seen = (); my @unique = grep { ! $seen{ $_ }++ } @array;</code></pre> <h2 id="How-can-I-tell-whether-a-certain-element-is-contained-in-a-list-or-array?"><a class="permalink" href="#How-can-I-tell-whether-a-certain-element-is-contained-in-a-list-or-array?">#</a><a id="How36"></a><a id="How-can-I-tell-whether-a-certain-element-is-contained-in-a-list-or-array"></a>How can I tell whether a certain element is contained in a list or array?</h2> <p>(portions of this answer contributed by Anno Siegel and brian d foy)</p> <p>Hearing the word &quot;in&quot; is an <i>in</i>dication that you probably should have used a hash, not a list or array, to store your data. Hashes are designed to answer this question quickly and efficiently. Arrays aren&#39;t.</p> <p>That being said, there are several ways to approach this. In Perl 5.10 and later, you can use the smart match operator to check that an item is contained in an array or a hash:</p> <pre><code>use 5.010; if( $item ~~ @array ) { say &quot;The array contains $item&quot; } if( $item ~~ %hash ) { say &quot;The hash contains $item&quot; }</code></pre> <p>With earlier versions of Perl, you have to do a bit more work. If you are going to make this query many times over arbitrary string values, the fastest way is probably to invert the original array and maintain a hash whose keys are the first array&#39;s values:</p> <pre><code>@blues = qw/azure cerulean teal turquoise lapis-lazuli/; %is_blue = (); for (@blues) { $is_blue{$_} = 1 }</code></pre> <p>Now you can check whether <code>$is_blue{$some_color}</code>. It might have been a good idea to keep the blues all in a hash in the first place.</p> <p>If the values are all small integers, you could use a simple indexed array. This kind of an array will take up less space:</p> <pre><code>@primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31); @is_tiny_prime = (); for (@primes) { $is_tiny_prime[$_] = 1 } # or simply @istiny_prime[@primes] = (1) x @primes;</code></pre> <p>Now you check whether $is_tiny_prime[$some_number].</p> <p>If the values in question are integers instead of strings, you can save quite a lot of space by using bit strings instead:</p> <pre><code>@articles = ( 1..10, 150..2000, 2017 ); undef $read; for (@articles) { vec($read,$_,1) = 1 }</code></pre> <p>Now check whether <code>vec($read,$n,1)</code> is true for some <code>$n</code>.</p> <p>These methods guarantee fast individual tests but require a re-organization of the original list or array. They only pay off if you have to test multiple values against the same array.</p> <p>If you are testing only once, the standard module <code>List::Util</code> exports the function <code>first</code> for this purpose. It works by stopping once it finds the element. It&#39;s written in C for speed, and its Perl equivalent looks like this subroutine:</p> <pre><code>sub first (&amp;@) { my $code = shift; foreach (@_) { return $_ if &amp;{$code}(); } undef; }</code></pre> <p>If speed is of little concern, the common idiom uses grep in scalar context (which returns the number of items that passed its condition) to traverse the entire list. This does have the benefit of telling you how many matches it found, though.</p> <pre><code>my $is_there = grep $_ eq $whatever, @array;</code></pre> <p>If you want to actually extract the matching elements, simply use grep in list context.</p> <pre><code>my @matches = grep $_ eq $whatever, @array;</code></pre> <h2 id="How-do-I-compute-the-difference-of-two-arrays?-How-do-I-compute-the-intersection-of-two-arrays?"><a class="permalink" href="#How-do-I-compute-the-difference-of-two-arrays?-How-do-I-compute-the-intersection-of-two-arrays?">#</a><a id="How37"></a><a id="How-do-I-compute-the-difference-of-two-arrays-How-do-I-compute-the-intersection-of-two-arrays"></a>How do I compute the difference of two arrays? How do I compute the intersection of two arrays?</h2> <p>Use a hash. Here&#39;s code to do both and more. It assumes that each element is unique in a given array:</p> <pre><code>@union = @intersection = @difference = (); %count = (); foreach $element (@array1, @array2) { $count{$element}++ } foreach $element (keys %count) { push @union, $element; push @{ $count{$element} &gt; 1 ? \@intersection : \@difference }, $element; }</code></pre> <p>Note that this is the <i>symmetric difference</i>, that is, all elements in either A or in B but not in both. Think of it as an xor operation.</p> <h2 id="How-do-I-test-whether-two-arrays-or-hashes-are-equal?"><a class="permalink" href="#How-do-I-test-whether-two-arrays-or-hashes-are-equal?">#</a><a id="How38"></a><a id="How-do-I-test-whether-two-arrays-or-hashes-are-equal"></a>How do I test whether two arrays or hashes are equal?</h2> <p>With Perl 5.10 and later, the smart match operator can give you the answer with the least amount of work:</p> <pre><code>use 5.010; if( @array1 ~~ @array2 ) { say &quot;The arrays are the same&quot;; } if( %hash1 ~~ %hash2 ) # doesn&#39;t check values! { say &quot;The hash keys are the same&quot;; }</code></pre> <p>The following code works for single-level arrays. It uses a stringwise comparison, and does not distinguish defined versus undefined empty strings. Modify if you have other needs.</p> <pre><code>$are_equal = compare_arrays(\@frogs, \@toads); sub compare_arrays { my ($first, $second) = @_; no warnings; # silence spurious -w undef complaints return 0 unless @$first == @$second; for (my $i = 0; $i &lt; @$first; $i++) { return 0 if $first-&gt;[$i] ne $second-&gt;[$i]; } return 1; }</code></pre> <p>For multilevel structures, you may wish to use an approach more like this one. It uses the CPAN module <code>FreezeThaw</code>:</p> <pre><code>use FreezeThaw qw(cmpStr); @a = @b = ( &quot;this&quot;, &quot;that&quot;, [ &quot;more&quot;, &quot;stuff&quot; ] ); printf &quot;a and b contain %s arrays\n&quot;, cmpStr(\@a, \@b) == 0 ? &quot;the same&quot; : &quot;different&quot;;</code></pre> <p>This approach also works for comparing hashes. Here we&#39;ll demonstrate two different answers:</p> <pre><code>use FreezeThaw qw(cmpStr cmpStrHard); %a = %b = ( &quot;this&quot; =&gt; &quot;that&quot;, &quot;extra&quot; =&gt; [ &quot;more&quot;, &quot;stuff&quot; ] ); $a{EXTRA} = \%b; $b{EXTRA} = \%a; printf &quot;a and b contain %s hashes\n&quot;, cmpStr(\%a, \%b) == 0 ? &quot;the same&quot; : &quot;different&quot;; printf &quot;a and b contain %s hashes\n&quot;, cmpStrHard(\%a, \%b) == 0 ? &quot;the same&quot; : &quot;different&quot;;</code></pre> <p>The first reports that both those the hashes contain the same data, while the second reports that they do not. Which you prefer is left as an exercise to the reader.</p> <h2 id="How-do-I-find-the-first-array-element-for-which-a-condition-is-true?"><a class="permalink" href="#How-do-I-find-the-first-array-element-for-which-a-condition-is-true?">#</a><a id="How39"></a><a id="How-do-I-find-the-first-array-element-for-which-a-condition-is-true"></a>How do I find the first array element for which a condition is true?</h2> <p>To find the first array element which satisfies a condition, you can use the <code>first()</code> function in the <code>List::Util</code> module, which comes with Perl 5.8. This example finds the first element that contains &quot;Perl&quot;.</p> <pre><code>use List::Util qw(first); my $element = first { /Perl/ } @array;</code></pre> <p>If you cannot use <code>List::Util</code>, you can make your own loop to do the same thing. Once you find the element, you stop the loop with last.</p> <pre><code>my $found; foreach ( @array ) { if( /Perl/ ) { $found = $_; last } }</code></pre> <p>If you want the array index, you can iterate through the indices and check the array element at each index until you find one that satisfies the condition.</p> <pre><code>my( $found, $index ) = ( undef, -1 ); for( $i = 0; $i &lt; @array; $i++ ) { if( $array[$i] =~ /Perl/ ) { $found = $array[$i]; $index = $i; last; } }</code></pre> <h2 id="How-do-I-handle-linked-lists?"><a class="permalink" href="#How-do-I-handle-linked-lists?">#</a><a id="How40"></a><a id="How-do-I-handle-linked-lists"></a>How do I handle linked lists?</h2> <p>In general, you usually don&#39;t need a linked list in Perl, since with regular arrays, you can push and pop or shift and unshift at either end, or you can use splice to add and/or remove arbitrary number of elements at arbitrary points. Both pop and shift are O(1) operations on Perl&#39;s dynamic arrays. In the absence of shifts and pops, push in general needs to reallocate on the order every log(N) times, and unshift will need to copy pointers each time.</p> <p>If you really, really wanted, you could use structures as described in <a href="/5.12.3/perldsc">perldsc</a> or <a href="/5.12.3/perltoot">perltoot</a> and do just what the algorithm book tells you to do. For example, imagine a list node like this:</p> <pre><code>$node = { VALUE =&gt; 42, LINK =&gt; undef, };</code></pre> <p>You could walk the list this way:</p> <pre><code>print &quot;List: &quot;; for ($node = $head; $node; $node = $node-&gt;{LINK}) { print $node-&gt;{VALUE}, &quot; &quot;; } print &quot;\n&quot;;</code></pre> <p>You could add to the list this way:</p> <pre><code>my ($head, $tail); $tail = append($head, 1); # grow a new head for $value ( 2 .. 10 ) { $tail = append($tail, $value); } sub append { my($list, $value) = @_; my $node = { VALUE =&gt; $value }; if ($list) { $node-&gt;{LINK} = $list-&gt;{LINK}; $list-&gt;{LINK} = $node; } else { $_[0] = $node; # replace caller&#39;s version } return $node; }</code></pre> <p>But again, Perl&#39;s built-in are virtually always good enough.</p> <h2 id="How-do-I-handle-circular-lists?"><a class="permalink" href="#How-do-I-handle-circular-lists?">#</a><a id="How41"></a><a id="How-do-I-handle-circular-lists"></a>How do I handle circular lists? </h2> <p>(contributed by brian d foy)</p> <p>If you want to cycle through an array endlessly, you can increment the index modulo the number of elements in the array:</p> <pre><code>my @array = qw( a b c ); my $i = 0; while( 1 ) { print $array[ $i++ % @array ], &quot;\n&quot;; last if $i &gt; 20; }</code></pre> <p>You can also use <code>Tie::Cycle</code> to use a scalar that always has the next element of the circular array:</p> <pre><code>use Tie::Cycle; tie my $cycle, &#39;Tie::Cycle&#39;, [ qw( FFFFFF 000000 FFFF00 ) ]; print $cycle; # FFFFFF print $cycle; # 000000 print $cycle; # FFFF00</code></pre> <p>The <code>Array::Iterator::Circular</code> creates an iterator object for circular arrays:</p> <pre><code>use Array::Iterator::Circular; my $color_iterator = Array::Iterator::Circular-&gt;new( qw(red green blue orange) ); foreach ( 1 .. 20 ) { print $color_iterator-&gt;next, &quot;\n&quot;; }</code></pre> <h2 id="How-do-I-shuffle-an-array-randomly?"><a class="permalink" href="#How-do-I-shuffle-an-array-randomly?">#</a><a id="How42"></a><a id="How-do-I-shuffle-an-array-randomly"></a>How do I shuffle an array randomly?</h2> <p>If you either have Perl 5.8.0 or later installed, or if you have Scalar-List-Utils 1.03 or later installed, you can say:</p> <pre><code>use List::Util &#39;shuffle&#39;; @shuffled = shuffle(@list);</code></pre> <p>If not, you can use a Fisher-Yates shuffle.</p> <pre><code>sub fisher_yates_shuffle { my $deck = shift; # $deck is a reference to an array return unless @$deck; # must not be empty! my $i = @$deck; while (--$i) { my $j = int rand ($i+1); @$deck[$i,$j] = @$deck[$j,$i]; } } # shuffle my mpeg collection # my @mpeg = &lt;audio/*/*.mp3&gt;; fisher_yates_shuffle( \@mpeg ); # randomize @mpeg in place print @mpeg;</code></pre> <p>Note that the above implementation shuffles an array in place, unlike the <code>List::Util::shuffle()</code> which takes a list and returns a new shuffled list.</p> <p>You&#39;ve probably seen shuffling algorithms that work using splice, randomly picking another element to swap the current element with</p> <pre><code>srand; @new = (); @old = 1 .. 10; # just a demo while (@old) { push(@new, splice(@old, rand @old, 1)); }</code></pre> <p>This is bad because splice is already O(N), and since you do it N times, you just invented a quadratic algorithm; that is, O(N**2). This does not scale, although Perl is so efficient that you probably won&#39;t notice this until you have rather largish arrays.</p> <h2 id="How-do-I-process/modify-each-element-of-an-array?"><a class="permalink" href="#How-do-I-process/modify-each-element-of-an-array?">#</a><a id="How43"></a><a id="How-do-I-process-modify-each-element-of-an-array"></a>How do I process/modify each element of an array?</h2> <p>Use <code>for</code>/<code>foreach</code>:</p> <pre><code>for (@lines) { s/foo/bar/; # change that word tr/XZ/ZX/; # swap those letters }</code></pre> <p>Here&#39;s another; let&#39;s compute spherical volumes:</p> <pre><code>for (@volumes = @radii) { # @volumes has changed parts $_ **= 3; $_ *= (4/3) * 3.14159; # this will be constant folded }</code></pre> <p>which can also be done with <code>map()</code> which is made to transform one list into another:</p> <pre><code>@volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;</code></pre> <p>If you want to do the same thing to modify the values of the hash, you can use the <code>values</code> function. As of Perl 5.6 the values are not copied, so if you modify $orbit (in this case), you modify the value.</p> <pre><code>for $orbit ( values %orbits ) { ($orbit **= 3) *= (4/3) * 3.14159; }</code></pre> <p>Prior to perl 5.6 <code>values</code> returned copies of the values, so older perl code often contains constructions such as <code>@orbits{keys %orbits}</code> instead of <code>values %orbits</code> where the hash is to be modified.</p> <h2 id="How-do-I-select-a-random-element-from-an-array?"><a class="permalink" href="#How-do-I-select-a-random-element-from-an-array?">#</a><a id="How44"></a><a id="How-do-I-select-a-random-element-from-an-array"></a>How do I select a random element from an array?</h2> <p>Use the <code>rand()</code> function (see <a href="/5.12.3/perlfunc#rand">&quot;rand&quot; in perlfunc</a>):</p> <pre><code>$index = rand @array; $element = $array[$index];</code></pre> <p>Or, simply:</p> <pre><code>my $element = $array[ rand @array ];</code></pre> <h2 id="How-do-I-permute-N-elements-of-a-list?"><a class="permalink" href="#How-do-I-permute-N-elements-of-a-list?">#</a><a id="How45"></a><a id="How-do-I-permute-N-elements-of-a-list"></a>How do I permute N elements of a list? </h2> <p>Use the <code>List::Permutor</code> module on CPAN. If the list is actually an array, try the <code>Algorithm::Permute</code> module (also on CPAN). It&#39;s written in XS code and is very efficient:</p> <pre><code>use Algorithm::Permute; my @array = &#39;a&#39;..&#39;d&#39;; my $p_iterator = Algorithm::Permute-&gt;new ( \@array ); while (my @perm = $p_iterator-&gt;next) { print &quot;next permutation: (@perm)\n&quot;; }</code></pre> <p>For even faster execution, you could do:</p> <pre><code>use Algorithm::Permute; my @array = &#39;a&#39;..&#39;d&#39;; Algorithm::Permute::permute { print &quot;next permutation: (@array)\n&quot;; } @array;</code></pre> <p>Here&#39;s a little program that generates all permutations of all the words on each line of input. The algorithm embodied in the <code>permute()</code> function is discussed in Volume 4 (still unpublished) of Knuth&#39;s <i>The Art of Computer Programming</i> and will work on any list:</p> <pre><code>#!/usr/bin/perl -n # Fischer-Krause ordered permutation generator sub permute (&amp;@) { my $code = shift; my @idx = 0..$#_; while ( $code-&gt;(@_[@idx]) ) { my $p = $#idx; --$p while $idx[$p-1] &gt; $idx[$p]; my $q = $p or return; push @idx, reverse splice @idx, $p; ++$q while $idx[$p-1] &gt; $idx[$q]; @idx[$p-1,$q]=@idx[$q,$p-1]; } } permute { print &quot;@_\n&quot; } split;</code></pre> <p>The <code>Algorithm::Loops</code> module also provides the <code>NextPermute</code> and <code>NextPermuteNum</code> functions which efficiently find all unique permutations of an array, even if it contains duplicate values, modifying it in-place: if its elements are in reverse-sorted order then the array is reversed, making it sorted, and it returns false; otherwise the next permutation is returned.</p> <p><code>NextPermute</code> uses string order and <code>NextPermuteNum</code> numeric order, so you can enumerate all the permutations of <code>0..9</code> like this:</p> <pre><code> use Algorithm::Loops qw(NextPermuteNum); my @list= 0..9; do { print &quot;@list\n&quot; } while NextPermuteNum @list;</code></pre> <h2 id="How-do-I-sort-an-array-by-(anything)?"><a class="permalink" href="#How-do-I-sort-an-array-by-(anything)?">#</a><a id="How46"></a><a id="How-do-I-sort-an-array-by-anything"></a>How do I sort an array by (anything)?</h2> <p>Supply a comparison function to sort() (described in <a href="/5.12.3/perlfunc#sort">&quot;sort&quot; in perlfunc</a>):</p> <pre><code>@list = sort { $a &lt;=&gt; $b } @list;</code></pre> <p>The default sort function is cmp, string comparison, which would sort <code>(1, 2, 10)</code> into <code>(1, 10, 2)</code>. <code>&lt;=&gt;</code>, used above, is the numerical comparison operator.</p> <p>If you have a complicated function needed to pull out the part you want to sort on, then don&#39;t do it inside the sort function. Pull it out first, because the sort BLOCK can be called many times for the same element. Here&#39;s an example of how to pull out the first word after the first number on each item, and then sort those words case-insensitively.</p> <pre><code>@idx = (); for (@data) { ($item) = /\d+\s*(\S+)/; push @idx, uc($item); } @sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];</code></pre> <p>which could also be written this way, using a trick that&#39;s come to be known as the Schwartzian Transform:</p> <pre><code>@sorted = map { $_-&gt;[0] } sort { $a-&gt;[1] cmp $b-&gt;[1] } map { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;</code></pre> <p>If you need to sort on several fields, the following paradigm is useful.</p> <pre><code>@sorted = sort { field1($a) &lt;=&gt; field1($b) || field2($a) cmp field2($b) || field3($a) cmp field3($b) } @data;</code></pre> <p>This can be conveniently combined with precalculation of keys as given above.</p> <p>See the <i>sort</i> article in the &quot;Far More Than You Ever Wanted To Know&quot; collection in http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz for more about this approach.</p> <p>See also the question later in <a href="/5.12.3/perlfaq4">perlfaq4</a> on sorting hashes.</p> <h2 id="How-do-I-manipulate-arrays-of-bits?"><a class="permalink" href="#How-do-I-manipulate-arrays-of-bits?">#</a><a id="How47"></a><a id="How-do-I-manipulate-arrays-of-bits"></a>How do I manipulate arrays of bits?</h2> <p>Use <code>pack()</code> and <code>unpack()</code>, or else <code>vec()</code> and the bitwise operations.</p> <p>For example, you don&#39;t have to store individual bits in an array (which would mean that you&#39;re wasting a lot of space). To convert an array of bits to a string, use <code>vec()</code> to set the right bits. This sets <code>$vec</code> to have bit N set only if <code>$ints[N]</code> was set:</p> <pre><code>@ints = (...); # array of bits, e.g. ( 1, 0, 0, 1, 1, 0 ... ) $vec = &#39;&#39;; foreach( 0 .. $#ints ) { vec($vec,$_,1) = 1 if $ints[$_]; }</code></pre> <p>The string <code>$vec</code> only takes up as many bits as it needs. For instance, if you had 16 entries in <code>@ints</code>, <code>$vec</code> only needs two bytes to store them (not counting the scalar variable overhead).</p> <p>Here&#39;s how, given a vector in <code>$vec</code>, you can get those bits into your <code>@ints</code> array:</p> <pre><code>sub bitvec_to_list { my $vec = shift; my @ints; # Find null-byte density then select best algorithm if ($vec =~ tr/\0// / length $vec &gt; 0.95) { use integer; my $i; # This method is faster with mostly null-bytes while($vec =~ /[^\0]/g ) { $i = -9 + 8 * pos $vec; push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); push @ints, $i if vec($vec, ++$i, 1); } } else { # This method is a fast general algorithm use integer; my $bits = unpack &quot;b*&quot;, $vec; push @ints, 0 if $bits =~ s/^(\d)// &amp;&amp; $1; push @ints, pos $bits while($bits =~ /1/g); } return \@ints; }</code></pre> <p>This method gets faster the more sparse the bit vector is. (Courtesy of Tim Bunce and Winfried Koenig.)</p> <p>You can make the while loop a lot shorter with this suggestion from Benjamin Goldberg:</p> <pre><code>while($vec =~ /[^\0]+/g ) { push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8; }</code></pre> <p>Or use the CPAN module <code>Bit::Vector</code>:</p> <pre><code>$vector = Bit::Vector-&gt;new($num_of_bits); $vector-&gt;Index_List_Store(@ints); @ints = $vector-&gt;Index_List_Read();</code></pre> <p><code>Bit::Vector</code> provides efficient methods for bit vector, sets of small integers and &quot;big int&quot; math.</p> <p>Here&#39;s a more extensive illustration using vec():</p> <pre><code># vec demo $vector = &quot;\xff\x0f\xef\xfe&quot;; print &quot;Ilya&#39;s string \\xff\\x0f\\xef\\xfe represents the number &quot;, unpack(&quot;N&quot;, $vector), &quot;\n&quot;; $is_set = vec($vector, 23, 1); print &quot;Its 23rd bit is &quot;, $is_set ? &quot;set&quot; : &quot;clear&quot;, &quot;.\n&quot;; pvec($vector); set_vec(1,1,1); set_vec(3,1,1); set_vec(23,1,1); set_vec(3,1,3); set_vec(3,2,3); set_vec(3,4,3); set_vec(3,4,7); set_vec(3,8,3); set_vec(3,8,7); set_vec(0,32,17); set_vec(1,32,17); sub set_vec { my ($offset, $width, $value) = @_; my $vector = &#39;&#39;; vec($vector, $offset, $width) = $value; print &quot;offset=$offset width=$width value=$value\n&quot;; pvec($vector); } sub pvec { my $vector = shift; my $bits = unpack(&quot;b*&quot;, $vector); my $i = 0; my $BASE = 8; print &quot;vector length in bytes: &quot;, length($vector), &quot;\n&quot;; @bytes = unpack(&quot;A8&quot; x length($vector), $bits); print &quot;bits are: @bytes\n\n&quot;; }</code></pre> <h2 id="Why-does-defined()-return-true-on-empty-arrays-and-hashes?"><a class="permalink" href="#Why-does-defined()-return-true-on-empty-arrays-and-hashes?">#</a><a id="Why6"></a><a id="Why-does-defined-return-true-on-empty-arrays-and-hashes"></a>Why does defined() return true on empty arrays and hashes?</h2> <p>The short story is that you should probably only use defined on scalars or functions, not on aggregates (arrays and hashes). See <a href="/5.12.3/perlfunc#defined">&quot;defined&quot; in perlfunc</a> in the 5.004 release or later of Perl for more detail.</p> <h1 id="Data:-Hashes-(Associative-Arrays)"><a class="permalink" href="#Data:-Hashes-(Associative-Arrays)">#</a><a id="Data4"></a><a id="Data:-Hashes-Associative-Arrays"></a>Data: Hashes (Associative Arrays)</h1> <h2 id="How-do-I-process-an-entire-hash?"><a class="permalink" href="#How-do-I-process-an-entire-hash?">#</a><a id="How48"></a><a id="How-do-I-process-an-entire-hash"></a>How do I process an entire hash?</h2> <p>(contributed by brian d foy)</p> <p>There are a couple of ways that you can process an entire hash. You can get a list of keys, then go through each key, or grab a one key-value pair at a time.</p> <p>To go through all of the keys, use the <code>keys</code> function. This extracts all of the keys of the hash and gives them back to you as a list. You can then get the value through the particular key you&#39;re processing:</p> <pre><code>foreach my $key ( keys %hash ) { my $value = $hash{$key} ... }</code></pre> <p>Once you have the list of keys, you can process that list before you process the hash elements. For instance, you can sort the keys so you can process them in lexical order:</p> <pre><code>foreach my $key ( sort keys %hash ) { my $value = $hash{$key} ... }</code></pre> <p>Or, you might want to only process some of the items. If you only want to deal with the keys that start with <code>text:</code>, you can select just those using <code>grep</code>:</p> <pre><code>foreach my $key ( grep /^text:/, keys %hash ) { my $value = $hash{$key} ... }</code></pre> <p>If the hash is very large, you might not want to create a long list of keys. To save some memory, you can grab one key-value pair at a time using <code>each()</code>, which returns a pair you haven&#39;t seen yet:</p> <pre><code>while( my( $key, $value ) = each( %hash ) ) { ... }</code></pre> <p>The <code>each</code> operator returns the pairs in apparently random order, so if ordering matters to you, you&#39;ll have to stick with the <code>keys</code> method.</p> <p>The <code>each()</code> operator can be a bit tricky though. You can&#39;t add or delete keys of the hash while you&#39;re using it without possibly skipping or re-processing some pairs after Perl internally rehashes all of the elements. Additionally, a hash has only one iterator, so if you use <code>keys</code>, <code>values</code>, or <code>each</code> on the same hash, you can reset the iterator and mess up your processing. See the <code>each</code> entry in <a href="/5.12.3/perlfunc">perlfunc</a> for more details.</p> <h2 id="How-do-I-merge-two-hashes?"><a class="permalink" href="#How-do-I-merge-two-hashes?">#</a><a id="How49"></a><a id="How-do-I-merge-two-hashes"></a>How do I merge two hashes? </h2> <p>(contributed by brian d foy)</p> <p>Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.</p> <p>If you want to preserve the original hashes, copy one hash (<code>%hash1</code>) to a new hash (<code>%new_hash</code>), then add the keys from the other hash (<code>%hash2</code> to the new hash. Checking that the key already exists in <code>%new_hash</code> gives you a chance to decide what to do with the duplicates:</p> <pre><code>my %new_hash = %hash1; # make a copy; leave %hash1 alone foreach my $key2 ( keys %hash2 ) { if( exists $new_hash{$key2} ) { warn &quot;Key [$key2] is in both hashes!&quot;; # handle the duplicate (perhaps only warning) ... next; } else { $new_hash{$key2} = $hash2{$key2}; } }</code></pre> <p>If you don&#39;t want to create a new hash, you can still use this looping technique; just change the <code>%new_hash</code> to <code>%hash1</code>.</p> <pre><code>foreach my $key2 ( keys %hash2 ) { if( exists $hash1{$key2} ) { warn &quot;Key [$key2] is in both hashes!&quot;; # handle the duplicate (perhaps only warning) ... next; } else { $hash1{$key2} = $hash2{$key2}; } }</code></pre> <p>If you don&#39;t care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from <code>%hash2</code> replace values from <code>%hash1</code> when they have keys in common:</p> <pre><code>@hash1{ keys %hash2 } = values %hash2;</code></pre> <h2 id="What-happens-if-I-add-or-remove-keys-from-a-hash-while-iterating-over-it?"><a class="permalink" href="#What-happens-if-I-add-or-remove-keys-from-a-hash-while-iterating-over-it?">#</a><a id="What3"></a><a id="What-happens-if-I-add-or-remove-keys-from-a-hash-while-iterating-over-it"></a>What happens if I add or remove keys from a hash while iterating over it?</h2> <p>(contributed by brian d foy)</p> <p>The easy answer is &quot;Don&#39;t do that!&quot;</p> <p>If you iterate through the hash with each(), you can delete the key most recently returned without worrying about it. If you delete or add other keys, the iterator may skip or double up on them since perl may rearrange the hash table. See the entry for <code>each()</code> in <a href="/5.12.3/perlfunc">perlfunc</a>.</p> <h2 id="How-do-I-look-up-a-hash-element-by-value?"><a class="permalink" href="#How-do-I-look-up-a-hash-element-by-value?">#</a><a id="How50"></a><a id="How-do-I-look-up-a-hash-element-by-value"></a>How do I look up a hash element by value?</h2> <p>Create a reverse hash:</p> <pre><code>%by_value = reverse %by_key; $key = $by_value{$value};</code></pre> <p>That&#39;s not particularly efficient. It would be more space-efficient to use:</p> <pre><code>while (($key, $value) = each %by_key) { $by_value{$value} = $key; }</code></pre> <p>If your hash could have repeated values, the methods above will only find one of the associated keys. This may or may not worry you. If it does worry you, you can always reverse the hash into a hash of arrays instead:</p> <pre><code>while (($key, $value) = each %by_key) { push @{$key_list_by_value{$value}}, $key; }</code></pre> <h2 id="How-can-I-know-how-many-entries-are-in-a-hash?"><a class="permalink" href="#How-can-I-know-how-many-entries-are-in-a-hash?">#</a><a id="How51"></a><a id="How-can-I-know-how-many-entries-are-in-a-hash"></a>How can I know how many entries are in a hash?</h2> <p>(contributed by brian d foy)</p> <p>This is very similar to &quot;How do I process an entire hash?&quot;, also in <a href="/5.12.3/perlfaq4">perlfaq4</a>, but a bit simpler in the common cases.</p> <p>You can use the <code>keys()</code> built-in function in scalar context to find out have many entries you have in a hash:</p> <pre><code>my $key_count = keys %hash; # must be scalar context!</code></pre> <p>If you want to find out how many entries have a defined value, that&#39;s a bit different. You have to check each value. A <code>grep</code> is handy:</p> <pre><code>my $defined_value_count = grep { defined } values %hash;</code></pre> <p>You can use that same structure to count the entries any way that you like. If you want the count of the keys with vowels in them, you just test for that instead:</p> <pre><code>my $vowel_count = grep { /[aeiou]/ } keys %hash;</code></pre> <p>The <code>grep</code> in scalar context returns the count. If you want the list of matching items, just use it in list context instead:</p> <pre><code>my @defined_values = grep { defined } values %hash;</code></pre> <p>The <code>keys()</code> function also resets the iterator, which means that you may see strange results if you use this between uses of other hash operators such as <code>each()</code>.</p> <h2 id="How-do-I-sort-a-hash-(optionally-by-value-instead-of-key)?"><a class="permalink" href="#How-do-I-sort-a-hash-(optionally-by-value-instead-of-key)?">#</a><a id="How52"></a><a id="How-do-I-sort-a-hash-optionally-by-value-instead-of-key"></a>How do I sort a hash (optionally by value instead of key)?</h2> <p>(contributed by brian d foy)</p> <p>To sort a hash, start with the keys. In this example, we give the list of keys to the sort function which then compares them ASCIIbetically (which might be affected by your locale settings). The output list has the keys in ASCIIbetical order. Once we have the keys, we can go through them to create a report which lists the keys in ASCIIbetical order.</p> <pre><code>my @keys = sort { $a cmp $b } keys %hash; foreach my $key ( @keys ) { printf &quot;%-20s %6d\n&quot;, $key, $hash{$key}; }</code></pre> <p>We could get more fancy in the <code>sort()</code> block though. Instead of comparing the keys, we can compute a value with them and use that value as the comparison.</p> <p>For instance, to make our report order case-insensitive, we use the <code>\L</code> sequence in a double-quoted string to make everything lowercase. The <code>sort()</code> block then compares the lowercased values to determine in which order to put the keys.</p> <pre><code>my @keys = sort { &quot;\L$a&quot; cmp &quot;\L$b&quot; } keys %hash;</code></pre> <p>Note: if the computation is expensive or the hash has many elements, you may want to look at the Schwartzian Transform to cache the computation results.</p> <p>If we want to sort by the hash value instead, we use the hash key to look it up. We still get out a list of keys, but this time they are ordered by their value.</p> <pre><code>my @keys = sort { $hash{$a} &lt;=&gt; $hash{$b} } keys %hash;</code></pre> <p>From there we can get more complex. If the hash values are the same, we can provide a secondary sort on the hash key.</p> <pre><code>my @keys = sort { $hash{$a} &lt;=&gt; $hash{$b} or &quot;\L$a&quot; cmp &quot;\L$b&quot; } keys %hash;</code></pre> <h2 id="How-can-I-always-keep-my-hash-sorted?"><a class="permalink" href="#How-can-I-always-keep-my-hash-sorted?">#</a><a id="How53"></a><a id="How-can-I-always-keep-my-hash-sorted"></a>How can I always keep my hash sorted? </h2> <p>You can look into using the <code>DB_File</code> module and <code>tie()</code> using the <code>$DB_BTREE</code> hash bindings as documented in <a href="/5.12.3/DB_File#In-Memory-Databases">&quot;In Memory Databases&quot; in DB_File</a>. The <code>Tie::IxHash</code> module from CPAN might also be instructive. Although this does keep your hash sorted, you might not like the slow down you suffer from the tie interface. Are you sure you need to do this? :)</p> <h2 id="What&#39;s-the-difference-between-&quot;delete&quot;-and-&quot;undef&quot;-with-hashes?"><a class="permalink" href="#What&#39;s-the-difference-between-%22delete%22-and-%22undef%22-with-hashes?">#</a><a id="What4"></a><a id="Whats-the-difference-between-delete-and-undef-with-hashes"></a>What&#39;s the difference between &quot;delete&quot; and &quot;undef&quot; with hashes?</h2> <p>Hashes contain pairs of scalars: the first is the key, the second is the value. The key will be coerced to a string, although the value can be any kind of scalar: string, number, or reference. If a key <code>$key</code> is present in %hash, <code>exists($hash{$key})</code> will return true. The value for a given key can be <code>undef</code>, in which case <code>$hash{$key}</code> will be <code>undef</code> while <code>exists $hash{$key}</code> will return true. This corresponds to (<code>$key</code>, <code>undef</code>) being in the hash.</p> <p>Pictures help... Here&#39;s the <code>%hash</code> table:</p> <pre><code class="plaintext"> keys values +------+------+ | a | 3 | | x | 7 | | d | 0 | | e | 2 | +------+------+</code></pre> <p>And these conditions hold</p> <pre><code>$hash{&#39;a&#39;} is true $hash{&#39;d&#39;} is false defined $hash{&#39;d&#39;} is true defined $hash{&#39;a&#39;} is true exists $hash{&#39;a&#39;} is true (Perl 5 only) grep ($_ eq &#39;a&#39;, keys %hash) is true</code></pre> <p>If you now say</p> <pre><code>undef $hash{&#39;a&#39;}</code></pre> <p>your table now reads:</p> <pre><code class="plaintext"> keys values +------+------+ | a | undef| | x | 7 | | d | 0 | | e | 2 | +------+------+</code></pre> <p>and these conditions now hold; changes in caps:</p> <pre><code>$hash{&#39;a&#39;} is FALSE $hash{&#39;d&#39;} is false defined $hash{&#39;d&#39;} is true defined $hash{&#39;a&#39;} is FALSE exists $hash{&#39;a&#39;} is true (Perl 5 only) grep ($_ eq &#39;a&#39;, keys %hash) is true</code></pre> <p>Notice the last two: you have an undef value, but a defined key!</p> <p>Now, consider this:</p> <pre><code>delete $hash{&#39;a&#39;}</code></pre> <p>your table now reads:</p> <pre><code class="plaintext"> keys values +------+------+ | x | 7 | | d | 0 | | e | 2 | +------+------+</code></pre> <p>and these conditions now hold; changes in caps:</p> <pre><code>$hash{&#39;a&#39;} is false $hash{&#39;d&#39;} is false defined $hash{&#39;d&#39;} is true defined $hash{&#39;a&#39;} is false exists $hash{&#39;a&#39;} is FALSE (Perl 5 only) grep ($_ eq &#39;a&#39;, keys %hash) is FALSE</code></pre> <p>See, the whole entry is gone!</p> <h2 id="Why-don&#39;t-my-tied-hashes-make-the-defined/exists-distinction?"><a class="permalink" href="#Why-don&#39;t-my-tied-hashes-make-the-defined/exists-distinction?">#</a><a id="Why7"></a><a id="Why-dont-my-tied-hashes-make-the-defined-exists-distinction"></a>Why don&#39;t my tied hashes make the defined/exists distinction?</h2> <p>This depends on the tied hash&#39;s implementation of EXISTS(). For example, there isn&#39;t the concept of undef with hashes that are tied to DBM* files. It also means that exists() and defined() do the same thing with a DBM* file, and what they end up doing is not what they do with ordinary hashes.</p> <h2 id="How-do-I-reset-an-each()-operation-part-way-through?"><a class="permalink" href="#How-do-I-reset-an-each()-operation-part-way-through?">#</a><a id="How54"></a><a id="How-do-I-reset-an-each-operation-part-way-through"></a>How do I reset an each() operation part-way through?</h2> <p>(contributed by brian d foy)</p> <p>You can use the <code>keys</code> or <code>values</code> functions to reset <code>each</code>. To simply reset the iterator used by <code>each</code> without doing anything else, use one of them in void context:</p> <pre><code>keys %hash; # resets iterator, nothing else. values %hash; # resets iterator, nothing else.</code></pre> <p>See the documentation for <code>each</code> in <a href="/5.12.3/perlfunc">perlfunc</a>.</p> <h2 id="How-can-I-get-the-unique-keys-from-two-hashes?"><a class="permalink" href="#How-can-I-get-the-unique-keys-from-two-hashes?">#</a><a id="How55"></a><a id="How-can-I-get-the-unique-keys-from-two-hashes"></a>How can I get the unique keys from two hashes?</h2> <p>First you extract the keys from the hashes into lists, then solve the &quot;removing duplicates&quot; problem described above. For example:</p> <pre><code>%seen = (); for $element (keys(%foo), keys(%bar)) { $seen{$element}++; } @uniq = keys %seen;</code></pre> <p>Or more succinctly:</p> <pre><code>@uniq = keys %{{%foo,%bar}};</code></pre> <p>Or if you really want to save space:</p> <pre><code>%seen = (); while (defined ($key = each %foo)) { $seen{$key}++; } while (defined ($key = each %bar)) { $seen{$key}++; } @uniq = keys %seen;</code></pre> <h2 id="How-can-I-store-a-multidimensional-array-in-a-DBM-file?"><a class="permalink" href="#How-can-I-store-a-multidimensional-array-in-a-DBM-file?">#</a><a id="How56"></a><a id="How-can-I-store-a-multidimensional-array-in-a-DBM-file"></a>How can I store a multidimensional array in a DBM file?</h2> <p>Either stringify the structure yourself (no fun), or else get the MLDBM (which uses Data::Dumper) module from CPAN and layer it on top of either DB_File or GDBM_File.</p> <h2 id="How-can-I-make-my-hash-remember-the-order-I-put-elements-into-it?"><a class="permalink" href="#How-can-I-make-my-hash-remember-the-order-I-put-elements-into-it?">#</a><a id="How57"></a><a id="How-can-I-make-my-hash-remember-the-order-I-put-elements-into-it"></a>How can I make my hash remember the order I put elements into it?</h2> <p>Use the <code>Tie::IxHash</code> from CPAN.</p> <pre><code>use Tie::IxHash; tie my %myhash, &#39;Tie::IxHash&#39;; for (my $i=0; $i&lt;20; $i++) { $myhash{$i} = 2*$i; } my @keys = keys %myhash; # @keys = (0,1,2,3,...)</code></pre> <h2 id="Why-does-passing-a-subroutine-an-undefined-element-in-a-hash-create-it?"><a class="permalink" href="#Why-does-passing-a-subroutine-an-undefined-element-in-a-hash-create-it?">#</a><a id="Why8"></a><a id="Why-does-passing-a-subroutine-an-undefined-element-in-a-hash-create-it"></a>Why does passing a subroutine an undefined element in a hash create it?</h2> <p>(contributed by brian d foy)</p> <p>Are you using a really old version of Perl?</p> <p>Normally, accessing a hash key&#39;s value for a nonexistent key will <i>not</i> create the key.</p> <pre><code>my %hash = (); my $value = $hash{ &#39;foo&#39; }; print &quot;This won&#39;t print\n&quot; if exists $hash{ &#39;foo&#39; };</code></pre> <p>Passing <code>$hash{ &#39;foo&#39; }</code> to a subroutine used to be a special case, though. Since you could assign directly to <code>$_[0]</code>, Perl had to be ready to make that assignment so it created the hash key ahead of time:</p> <pre><code> my_sub( $hash{ &#39;foo&#39; } ); print &quot;This will print before 5.004\n&quot; if exists $hash{ &#39;foo&#39; }; sub my_sub { # $_[0] = &#39;bar&#39;; # create hash key in case you do this 1; }</code></pre> <p>Since Perl 5.004, however, this situation is a special case and Perl creates the hash key only when you make the assignment:</p> <pre><code> my_sub( $hash{ &#39;foo&#39; } ); print &quot;This will print, even after 5.004\n&quot; if exists $hash{ &#39;foo&#39; }; sub my_sub { $_[0] = &#39;bar&#39;; }</code></pre> <p>However, if you want the old behavior (and think carefully about that because it&#39;s a weird side effect), you can pass a hash slice instead. Perl 5.004 didn&#39;t make this a special case:</p> <pre><code>my_sub( @hash{ qw/foo/ } );</code></pre> <h2 id="How-can-I-make-the-Perl-equivalent-of-a-C-structure/C++-class/hash-or-array-of-hashes-or-arrays?"><a class="permalink" href="#How-can-I-make-the-Perl-equivalent-of-a-C-structure/C++-class/hash-or-array-of-hashes-or-arrays?">#</a><a id="How58"></a><a id="How-can-I-make-the-Perl-equivalent-of-a-C-structure-C-class-hash-or-array-of-hashes-or-arrays"></a>How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?</h2> <p>Usually a hash ref, perhaps like this:</p> <pre><code>$record = { NAME =&gt; &quot;Jason&quot;, EMPNO =&gt; 132, TITLE =&gt; &quot;deputy peon&quot;, AGE =&gt; 23, SALARY =&gt; 37_000, PALS =&gt; [ &quot;Norbert&quot;, &quot;Rhys&quot;, &quot;Phineas&quot;], };</code></pre> <p>References are documented in <a href="/5.12.3/perlref">perlref</a> and the upcoming <a href="/5.12.3/perlreftut">perlreftut</a>. Examples of complex data structures are given in <a href="/5.12.3/perldsc">perldsc</a> and <a href="/5.12.3/perllol">perllol</a>. Examples of structures and object-oriented classes are in <a href="/5.12.3/perltoot">perltoot</a>.</p> <h2 id="How-can-I-use-a-reference-as-a-hash-key?"><a class="permalink" href="#How-can-I-use-a-reference-as-a-hash-key?">#</a><a id="How59"></a><a id="How-can-I-use-a-reference-as-a-hash-key"></a>How can I use a reference as a hash key?</h2> <p>(contributed by brian d foy and Ben Morrow)</p> <p>Hash keys are strings, so you can&#39;t really use a reference as the key. When you try to do that, perl turns the reference into its stringified form (for instance, <code>HASH(0xDEADBEEF)</code>). From there you can&#39;t get back the reference from the stringified form, at least without doing some extra work on your own.</p> <p>Remember that the entry in the hash will still be there even if the referenced variable goes out of scope, and that it is entirely possible for Perl to subsequently allocate a different variable at the same address. This will mean a new variable might accidentally be associated with the value for an old.</p> <p>If you have Perl 5.10 or later, and you just want to store a value against the reference for lookup later, you can use the core Hash::Util::Fieldhash module. This will also handle renaming the keys if you use multiple threads (which causes all variables to be reallocated at new addresses, changing their stringification), and garbage-collecting the entries when the referenced variable goes out of scope.</p> <p>If you actually need to be able to get a real reference back from each hash entry, you can use the Tie::RefHash module, which does the required work for you.</p> <h1 id="Data:-Misc"><a class="permalink" href="#Data:-Misc">#</a><a id="Data5"></a>Data: Misc</h1> <h2 id="How-do-I-handle-binary-data-correctly?"><a class="permalink" href="#How-do-I-handle-binary-data-correctly?">#</a><a id="How60"></a><a id="How-do-I-handle-binary-data-correctly"></a>How do I handle binary data correctly?</h2> <p>Perl is binary clean, so it can handle binary data just fine. On Windows or DOS, however, you have to use <code>binmode</code> for binary files to avoid conversions for line endings. In general, you should use <code>binmode</code> any time you want to work with binary data.</p> <p>Also see <a href="/5.12.3/perlfunc#binmode">&quot;binmode&quot; in perlfunc</a> or <a href="/5.12.3/perlopentut">perlopentut</a>.</p> <p>If you&#39;re concerned about 8-bit textual data then see <a href="/5.12.3/perllocale">perllocale</a>. If you want to deal with multibyte characters, however, there are some gotchas. See the section on Regular Expressions.</p> <h2 id="How-do-I-determine-whether-a-scalar-is-a-number/whole/integer/float?"><a class="permalink" href="#How-do-I-determine-whether-a-scalar-is-a-number/whole/integer/float?">#</a><a id="How61"></a><a id="How-do-I-determine-whether-a-scalar-is-a-number-whole-integer-float"></a>How do I determine whether a scalar is a number/whole/integer/float?</h2> <p>Assuming that you don&#39;t care about IEEE notations like &quot;NaN&quot; or &quot;Infinity&quot;, you probably just want to use a regular expression.</p> <pre><code class="plaintext">if (/\D/) { print &quot;has nondigits\n&quot; } if (/^\d+$/) { print &quot;is a whole number\n&quot; } if (/^-?\d+$/) { print &quot;is an integer\n&quot; } if (/^[+-]?\d+$/) { print &quot;is a +/- integer\n&quot; } if (/^-?\d+\.?\d*$/) { print &quot;is a real number\n&quot; } if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print &quot;is a decimal number\n&quot; } if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) { print &quot;a C float\n&quot; }</code></pre> <p>There are also some commonly used modules for the task. <a href="/5.12.3/Scalar::Util">Scalar::Util</a> (distributed with 5.8) provides access to perl&#39;s internal function <code>looks_like_number</code> for determining whether a variable looks like a number. <a href="/5.12.3/Data::Types">Data::Types</a> exports functions that validate data types using both the above and other regular expressions. Thirdly, there is <code>Regexp::Common</code> which has regular expressions to match various types of numbers. Those three modules are available from the CPAN.</p> <p>If you&#39;re on a POSIX system, Perl supports the <code>POSIX::strtod</code> function. Its semantics are somewhat cumbersome, so here&#39;s a <code>getnum</code> wrapper function for more convenient access. This function takes a string and returns the number it found, or <code>undef</code> for input that isn&#39;t a C float. The <code>is_numeric</code> function is a front end to <code>getnum</code> if you just want to say, &quot;Is this a float?&quot;</p> <pre><code>sub getnum { use POSIX qw(strtod); my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq &#39;&#39;) || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) }</code></pre> <p>Or you could check out the <a href="/5.12.3/String::Scanf">String::Scanf</a> module on the CPAN instead. The <code>POSIX</code> module (part of the standard Perl distribution) provides the <code>strtod</code> and <code>strtol</code> for converting strings to double and longs, respectively.</p> <h2 id="How-do-I-keep-persistent-data-across-program-calls?"><a class="permalink" href="#How-do-I-keep-persistent-data-across-program-calls?">#</a><a id="How62"></a><a id="How-do-I-keep-persistent-data-across-program-calls"></a>How do I keep persistent data across program calls?</h2> <p>For some specific applications, you can use one of the DBM modules. See <a href="/5.12.3/AnyDBM_File">AnyDBM_File</a>. More generically, you should consult the <code>FreezeThaw</code> or <code>Storable</code> modules from CPAN. Starting from Perl 5.8 <code>Storable</code> is part of the standard distribution. Here&#39;s one example using <code>Storable</code>&#39;s <code>store</code> and <code>retrieve</code> functions:</p> <pre><code>use Storable; store(\%hash, &quot;filename&quot;); # later on... $href = retrieve(&quot;filename&quot;); # by ref %hash = %{ retrieve(&quot;filename&quot;) }; # direct to hash</code></pre> <h2 id="How-do-I-print-out-or-copy-a-recursive-data-structure?"><a class="permalink" href="#How-do-I-print-out-or-copy-a-recursive-data-structure?">#</a><a id="How63"></a><a id="How-do-I-print-out-or-copy-a-recursive-data-structure"></a>How do I print out or copy a recursive data structure?</h2> <p>The <code>Data::Dumper</code> module on CPAN (or the 5.005 release of Perl) is great for printing out data structures. The <code>Storable</code> module on CPAN (or the 5.8 release of Perl), provides a function called <code>dclone</code> that recursively copies its argument.</p> <pre><code>use Storable qw(dclone); $r2 = dclone($r1);</code></pre> <p>Where <code>$r1</code> can be a reference to any kind of data structure you&#39;d like. It will be deeply copied. Because <code>dclone</code> takes and returns references, you&#39;d have to add extra punctuation if you had a hash of arrays that you wanted to copy.</p> <pre><code>%newhash = %{ dclone(\%oldhash) };</code></pre> <h2 id="How-do-I-define-methods-for-every-class/object?"><a class="permalink" href="#How-do-I-define-methods-for-every-class/object?">#</a><a id="How64"></a><a id="How-do-I-define-methods-for-every-class-object"></a>How do I define methods for every class/object?</h2> <p>(contributed by Ben Morrow)</p> <p>You can use the <code>UNIVERSAL</code> class (see <a href="/5.12.3/UNIVERSAL">UNIVERSAL</a>). However, please be very careful to consider the consequences of doing this: adding methods to every object is very likely to have unintended consequences. If possible, it would be better to have all your object inherit from some common base class, or to use an object system like Moose that supports roles.</p> <h2 id="How-do-I-verify-a-credit-card-checksum?"><a class="permalink" href="#How-do-I-verify-a-credit-card-checksum?">#</a><a id="How65"></a><a id="How-do-I-verify-a-credit-card-checksum"></a>How do I verify a credit card checksum?</h2> <p>Get the <code>Business::CreditCard</code> module from CPAN.</p> <h2 id="How-do-I-pack-arrays-of-doubles-or-floats-for-XS-code?"><a class="permalink" href="#How-do-I-pack-arrays-of-doubles-or-floats-for-XS-code?">#</a><a id="How66"></a><a id="How-do-I-pack-arrays-of-doubles-or-floats-for-XS-code"></a>How do I pack arrays of doubles or floats for XS code?</h2> <p>The arrays.h/arrays.c code in the <code>PGPLOT</code> module on CPAN does just this. If you&#39;re doing a lot of float or double processing, consider using the <code>PDL</code> module from CPAN instead--it makes number-crunching easy.</p> <p>See <a href="http://search.cpan.org/dist/PGPLOT">http://search.cpan.org/dist/PGPLOT</a> for the code.</p> <h1 id="AUTHOR-AND-COPYRIGHT"><a class="permalink" href="#AUTHOR-AND-COPYRIGHT">#</a><a id="AUTHOR"></a>AUTHOR AND COPYRIGHT</h1> <p>Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.</p> <p>This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.</p> <p>Irrespective of its distribution, all code examples in this file are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required.</p> </div> <div id="footer"> <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p> <p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10