CINXE.COM

perlfaq7 - Perl Language Issues ($Revision: 1.28 $, $Date: 1999/05/23 20:36:18 $) - 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>perlfaq7 - Perl Language Issues ($Revision: 1.28 $, $Date: 1999/05/23 20:36:18 $) - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/perlfaq7"> <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="/"><img src="/images/perl_camel_30.png" width="30" height="30" class="d-inline-block align-top" alt="Perl Camel Logo"> 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.6.1</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/perlfaq7">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1/perlfaq7">5.40.1</a> <a class="dropdown-item" href="/5.40.0/perlfaq7">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3/perlfaq7">5.38.3</a> <a class="dropdown-item" href="/5.38.2/perlfaq7">5.38.2</a> <a class="dropdown-item" href="/5.38.1/perlfaq7">5.38.1</a> <a class="dropdown-item" href="/5.38.0/perlfaq7">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/perlfaq7">5.36.3</a> <a class="dropdown-item" href="/5.36.2/perlfaq7">5.36.2</a> <a class="dropdown-item" href="/5.36.1/perlfaq7">5.36.1</a> <a class="dropdown-item" href="/5.36.0/perlfaq7">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/perlfaq7">5.34.3</a> <a class="dropdown-item" href="/5.34.2/perlfaq7">5.34.2</a> <a class="dropdown-item" href="/5.34.1/perlfaq7">5.34.1</a> <a class="dropdown-item" href="/5.34.0/perlfaq7">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/perlfaq7">5.32.1</a> <a class="dropdown-item" href="/5.32.0/perlfaq7">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/perlfaq7">5.30.3</a> <a class="dropdown-item" href="/5.30.2/perlfaq7">5.30.2</a> <a class="dropdown-item" href="/5.30.1/perlfaq7">5.30.1</a> <a class="dropdown-item" href="/5.30.0/perlfaq7">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/perlfaq7">5.28.3</a> <a class="dropdown-item" href="/5.28.2/perlfaq7">5.28.2</a> <a class="dropdown-item" href="/5.28.1/perlfaq7">5.28.1</a> <a class="dropdown-item" href="/5.28.0/perlfaq7">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/perlfaq7">5.26.3</a> <a class="dropdown-item" href="/5.26.2/perlfaq7">5.26.2</a> <a class="dropdown-item" href="/5.26.1/perlfaq7">5.26.1</a> <a class="dropdown-item" href="/5.26.0/perlfaq7">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/perlfaq7">5.24.4</a> <a class="dropdown-item" href="/5.24.3/perlfaq7">5.24.3</a> <a class="dropdown-item" href="/5.24.2/perlfaq7">5.24.2</a> <a class="dropdown-item" href="/5.24.1/perlfaq7">5.24.1</a> <a class="dropdown-item" href="/5.24.0/perlfaq7">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/perlfaq7">5.22.4</a> <a class="dropdown-item" href="/5.22.3/perlfaq7">5.22.3</a> <a class="dropdown-item" href="/5.22.2/perlfaq7">5.22.2</a> <a class="dropdown-item" href="/5.22.1/perlfaq7">5.22.1</a> <a class="dropdown-item" href="/5.22.0/perlfaq7">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/perlfaq7">5.20.3</a> <a class="dropdown-item" href="/5.20.2/perlfaq7">5.20.2</a> <a class="dropdown-item" href="/5.20.1/perlfaq7">5.20.1</a> <a class="dropdown-item" href="/5.20.0/perlfaq7">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/perlfaq7">5.18.4</a> <a class="dropdown-item" href="/5.18.3/perlfaq7">5.18.3</a> <a class="dropdown-item" href="/5.18.2/perlfaq7">5.18.2</a> <a class="dropdown-item" href="/5.18.1/perlfaq7">5.18.1</a> <a class="dropdown-item" href="/5.18.0/perlfaq7">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/perlfaq7">5.16.3</a> <a class="dropdown-item" href="/5.16.2/perlfaq7">5.16.2</a> <a class="dropdown-item" href="/5.16.1/perlfaq7">5.16.1</a> <a class="dropdown-item" href="/5.16.0/perlfaq7">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/perlfaq7">5.14.4</a> <a class="dropdown-item" href="/5.14.3/perlfaq7">5.14.3</a> <a class="dropdown-item" href="/5.14.2/perlfaq7">5.14.2</a> <a class="dropdown-item" href="/5.14.1/perlfaq7">5.14.1</a> <a class="dropdown-item" href="/5.14.0/perlfaq7">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/perlfaq7">5.12.5</a> <a class="dropdown-item" href="/5.12.4/perlfaq7">5.12.4</a> <a class="dropdown-item" href="/5.12.3/perlfaq7">5.12.3</a> <a class="dropdown-item" href="/5.12.2/perlfaq7">5.12.2</a> <a class="dropdown-item" href="/5.12.1/perlfaq7">5.12.1</a> <a class="dropdown-item" href="/5.12.0/perlfaq7">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/perlfaq7">5.10.1</a> <a class="dropdown-item" href="/5.10.0/perlfaq7">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/perlfaq7">5.8.9</a> <a class="dropdown-item" href="/5.8.8/perlfaq7">5.8.8</a> <a class="dropdown-item" href="/5.8.7/perlfaq7">5.8.7</a> <a class="dropdown-item" href="/5.8.6/perlfaq7">5.8.6</a> <a class="dropdown-item" href="/5.8.5/perlfaq7">5.8.5</a> <a class="dropdown-item" href="/5.8.4/perlfaq7">5.8.4</a> <a class="dropdown-item" href="/5.8.3/perlfaq7">5.8.3</a> <a class="dropdown-item" href="/5.8.2/perlfaq7">5.8.2</a> <a class="dropdown-item" href="/5.8.1/perlfaq7">5.8.1</a> <a class="dropdown-item" href="/5.8.0/perlfaq7">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/perlfaq7">5.6.2</a> <a class="dropdown-item active" href="/5.6.1/perlfaq7">5.6.1</a> <a class="dropdown-item" href="/5.6.0/perlfaq7">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/perlfaq7">5.005_04</a> <a class="dropdown-item" href="/5.005_03/perlfaq7">5.005_03</a> <a class="dropdown-item" href="/5.005_02/perlfaq7">5.005_02</a> <a class="dropdown-item" href="/5.005_01/perlfaq7">5.005_01</a> <a class="dropdown-item" href="/5.005/perlfaq7">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/perlfaq7">blead</a> <a class="dropdown-item" href="/5.41.10/perlfaq7">5.41.10</a> <a class="dropdown-item" href="/5.41.9/perlfaq7">5.41.9</a> <a class="dropdown-item" href="/5.41.8/perlfaq7">5.41.8</a> <a class="dropdown-item" href="/5.41.7/perlfaq7">5.41.7</a> <a class="dropdown-item" href="/5.41.6/perlfaq7">5.41.6</a> <a class="dropdown-item" href="/5.41.5/perlfaq7">5.41.5</a> <a class="dropdown-item" href="/5.41.4/perlfaq7">5.41.4</a> <a class="dropdown-item" href="/5.41.3/perlfaq7">5.41.3</a> <a class="dropdown-item" href="/5.41.2/perlfaq7">5.41.2</a> <a class="dropdown-item" href="/5.41.1/perlfaq7">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1-RC1/perlfaq7">5.40.1-RC1</a> <a class="dropdown-item" href="/5.40.0-RC2/perlfaq7">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/perlfaq7">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/perlfaq7">5.39.10</a> <a class="dropdown-item" href="/5.39.9/perlfaq7">5.39.9</a> <a class="dropdown-item" href="/5.39.8/perlfaq7">5.39.8</a> <a class="dropdown-item" href="/5.39.7/perlfaq7">5.39.7</a> <a class="dropdown-item" href="/5.39.6/perlfaq7">5.39.6</a> <a class="dropdown-item" href="/5.39.5/perlfaq7">5.39.5</a> <a class="dropdown-item" href="/5.39.4/perlfaq7">5.39.4</a> <a class="dropdown-item" href="/5.39.3/perlfaq7">5.39.3</a> <a class="dropdown-item" href="/5.39.2/perlfaq7">5.39.2</a> <a class="dropdown-item" href="/5.39.1/perlfaq7">5.39.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3-RC1/perlfaq7">5.38.3-RC1</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.6.1/perl">Perl</a> <a class="dropdown-item" href="/5.6.1/perlintro">Intro</a> <a class="dropdown-item" href="/5.6.1/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/5.6.1/perlfaq">FAQs</a> <a class="dropdown-item" href="/5.6.1/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.1/perlop">Operators</a> <a class="dropdown-item" href="/5.6.1/functions">Functions</a> <a class="dropdown-item" href="/5.6.1/variables">Variables</a> <a class="dropdown-item" href="/5.6.1/modules">Modules</a> <a class="dropdown-item" href="/5.6.1/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.1/perldelta">Release Notes</a> <a class="dropdown-item" href="/5.6.1/perlcommunity">Community</a> <a class="dropdown-item" href="/5.6.1/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.6.1/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.6.1/perlfaq7">perlfaq7</a> <div id="more"> (<a href="/5.6.1/perlfaq7.txt">source</a>, <a href="https://metacpan.org/pod/perlfaq7">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl 5.6.1. <a href="/perlfaq7">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> <ul> <li> <a class="text-decoration-none" href="#Can-I-get-a-BNF/yacc/RE-for-the-Perl-language?">Can I get a BNF/yacc/RE for the Perl language?</a> </li> <li> <a class="text-decoration-none" href="#What-are-all-these-$@%25&amp;*-punctuation-signs,-and-how-do-I-know-when-to-use-them?">What are all these $@%&amp;* punctuation signs, and how do I know when to use them?</a> </li> <li> <a class="text-decoration-none" href="#Do-I-always/never-have-to-quote-my-strings-or-use-semicolons-and-commas?">Do I always/never have to quote my strings or use semicolons and commas?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-skip-some-return-values?">How do I skip some return values?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-temporarily-block-warnings?">How do I temporarily block warnings?</a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-an-extension?">What&#39;s an extension?</a> </li> <li> <a class="text-decoration-none" href="#Why-do-Perl-operators-have-different-precedence-than-C-operators?">Why do Perl operators have different precedence than C operators?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-declare/create-a-structure?">How do I declare/create a structure?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-create-a-module?">How do I create a module?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-create-a-class?">How do I create a class?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-tell-if-a-variable-is-tainted?">How can I tell if a variable is tainted?</a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-a-closure?">What&#39;s a closure?</a> </li> <li> <a class="text-decoration-none" href="#What-is-variable-suicide-and-how-can-I-prevent-it?">What is variable suicide and how can I prevent it?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-pass/return-a-%7BFunction,-FileHandle,-Array,-Hash,-Method,-Regex%7D?">How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-create-a-static-variable?">How do I create a static variable?</a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-the-difference-between-dynamic-and-lexical-(static)-scoping?-Between-local()-and-my()?">What&#39;s the difference between dynamic and lexical (static) scoping? Between local() and my()?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-access-a-dynamic-variable-while-a-similarly-named-lexical-is-in-scope?">How can I access a dynamic variable while a similarly named lexical is in scope?</a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-the-difference-between-deep-and-shallow-binding?">What&#39;s the difference between deep and shallow binding?</a> </li> <li> <a class="text-decoration-none" href="#Why-doesn&#39;t-%22my($foo)-=-%3CFILE%3E;%22-work-right?">Why doesn&#39;t &quot;my($foo) = &lt;FILE&gt;;&quot; work right?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-redefine-a-builtin-function,-operator,-or-method?">How do I redefine a builtin function, operator, or method?</a> </li> <li> <a class="text-decoration-none" href="#What&#39;s-the-difference-between-calling-a-function-as-&amp;foo-and-foo()?">What&#39;s the difference between calling a function as &amp;foo and foo()?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-create-a-switch-or-case-statement?">How do I create a switch or case statement?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-catch-accesses-to-undefined-variables/functions/methods?">How can I catch accesses to undefined variables/functions/methods?</a> </li> <li> <a class="text-decoration-none" href="#Why-can&#39;t-a-method-included-in-this-same-file-be-found?">Why can&#39;t a method included in this same file be found?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-find-out-my-current-package?">How can I find out my current package?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-comment-out-a-large-block-of-perl-code?">How can I comment out a large block of perl code?</a> </li> <li> <a class="text-decoration-none" href="#How-do-I-clear-a-package?">How do I clear a package?</a> </li> <li> <a class="text-decoration-none" href="#How-can-I-use-a-variable-as-a-variable-name?">How can I use a variable as a variable name?</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>perlfaq7 - Perl Language Issues ($Revision: 1.28 $, $Date: 1999/05/23 20:36:18 $)</p> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>This section deals with general Perl language issues that don&#39;t clearly fit into any of the other sections.</p> <h2 id="Can-I-get-a-BNF/yacc/RE-for-the-Perl-language?"><a class="permalink" href="#Can-I-get-a-BNF/yacc/RE-for-the-Perl-language?">#</a><a id="Can"></a><a id="Can-I-get-a-BNF-yacc-RE-for-the-Perl-language"></a>Can I get a BNF/yacc/RE for the Perl language?</h2> <p>There is no BNF, but you can paw your way through the yacc grammar in perly.y in the source distribution if you&#39;re particularly brave. The grammar relies on very smart tokenizing code, so be prepared to venture into toke.c as well.</p> <p>In the words of Chaim Frenkel: &quot;Perl&#39;s grammar can not be reduced to BNF. The work of parsing perl is distributed between yacc, the lexer, smoke and mirrors.&quot;</p> <h2 id="What-are-all-these-$@%&amp;*-punctuation-signs,-and-how-do-I-know-when-to-use-them?"><a class="permalink" href="#What-are-all-these-$@%25&amp;*-punctuation-signs,-and-how-do-I-know-when-to-use-them?">#</a><a id="What"></a><a id="What-are-all-these-punctuation-signs-and-how-do-I-know-when-to-use-them"></a>What are all these $@%&amp;* punctuation signs, and how do I know when to use them?</h2> <p>They are type specifiers, as detailed in <a href="/5.6.1/perldata">perldata</a>:</p> <pre><code class="plaintext">$ for scalar values (number, string or reference) @ for arrays % for hashes (associative arrays) &amp; for subroutines (aka functions, procedures, methods) * for all types of that symbol name. In version 4 you used them like pointers, but in modern perls you can just use references.</code></pre> <p>There are couple of other symbols that you&#39;re likely to encounter that aren&#39;t really type specifiers:</p> <pre><code class="plaintext">&lt;&gt; are used for inputting a record from a filehandle. \ takes a reference to something.</code></pre> <p>Note that &lt;FILE&gt; is <i>neither</i> the type specifier for files nor the name of the handle. It is the <code>&lt;&gt;</code> operator applied to the handle FILE. It reads one line (well, record--see <a href="/5.6.1/perlvar#%24%2F">&quot;$/&quot; in perlvar</a>) from the handle FILE in scalar context, or <i>all</i> lines in list context. When performing open, close, or any other operation besides <code>&lt;&gt;</code> on files, or even when talking about the handle, do <i>not</i> use the brackets. These are correct: <code>eof(FH)</code>, <code>seek(FH, 0, 2)</code> and &quot;copying from STDIN to FILE&quot;.</p> <h2 id="Do-I-always/never-have-to-quote-my-strings-or-use-semicolons-and-commas?"><a class="permalink" href="#Do-I-always/never-have-to-quote-my-strings-or-use-semicolons-and-commas?">#</a><a id="Do"></a><a id="Do-I-always-never-have-to-quote-my-strings-or-use-semicolons-and-commas"></a>Do I always/never have to quote my strings or use semicolons and commas?</h2> <p>Normally, a bareword doesn&#39;t need to be quoted, but in most cases probably should be (and must be under <code>use strict</code>). But a hash key consisting of a simple word (that isn&#39;t the name of a defined subroutine) and the left-hand operand to the <code>=&gt;</code> operator both count as though they were quoted:</p> <pre><code>This is like this ------------ --------------- $foo{line} $foo{&quot;line&quot;} bar =&gt; stuff &quot;bar&quot; =&gt; stuff</code></pre> <p>The final semicolon in a block is optional, as is the final comma in a list. Good style (see <a href="/5.6.1/perlstyle">perlstyle</a>) says to put them in except for one-liners:</p> <pre><code> if ($whoops) { exit 1 } @nums = (1, 2, 3); if ($whoops) { exit 1; } @lines = ( &quot;There Beren came from mountains cold&quot;, &quot;And lost he wandered under leaves&quot;, );</code></pre> <h2 id="How-do-I-skip-some-return-values?"><a class="permalink" href="#How-do-I-skip-some-return-values?">#</a><a id="How"></a><a id="How-do-I-skip-some-return-values"></a>How do I skip some return values?</h2> <p>One way is to treat the return values as a list and index into it:</p> <pre><code>$dir = (getpwnam($user))[7];</code></pre> <p>Another way is to use undef as an element on the left-hand-side:</p> <pre><code>($dev, $ino, undef, undef, $uid, $gid) = stat($file);</code></pre> <h2 id="How-do-I-temporarily-block-warnings?"><a class="permalink" href="#How-do-I-temporarily-block-warnings?">#</a><a id="How1"></a><a id="How-do-I-temporarily-block-warnings"></a>How do I temporarily block warnings?</h2> <p>If you are running Perl 5.6.0 or better, the <code>use warnings</code> pragma allows fine control of what warning are produced. See <a href="/5.6.1/perllexwarn">perllexwarn</a> for more details.</p> <pre><code> { no warnings; # temporarily turn off warnings $a = $b + $c; # I know these might be undef }</code></pre> <p>If you have an older version of Perl, the <code>$^W</code> variable (documented in <a href="/5.6.1/perlvar">perlvar</a>) controls runtime warnings for a block:</p> <pre><code> { local $^W = 0; # temporarily turn off warnings $a = $b + $c; # I know these might be undef }</code></pre> <p>Note that like all the punctuation variables, you cannot currently use my() on <code>$^W</code>, only local().</p> <h2 id="What&#39;s-an-extension?"><a class="permalink" href="#What&#39;s-an-extension?">#</a><a id="What1"></a><a id="Whats-an-extension"></a>What&#39;s an extension?</h2> <p>An extension is a way of calling compiled C code from Perl. Reading <a href="/5.6.1/perlxstut">perlxstut</a> is a good place to learn more about extensions.</p> <h2 id="Why-do-Perl-operators-have-different-precedence-than-C-operators?"><a class="permalink" href="#Why-do-Perl-operators-have-different-precedence-than-C-operators?">#</a><a id="Why"></a><a id="Why-do-Perl-operators-have-different-precedence-than-C-operators"></a>Why do Perl operators have different precedence than C operators?</h2> <p>Actually, they don&#39;t. All C operators that Perl copies have the same precedence in Perl as they do in C. The problem is with operators that C doesn&#39;t have, especially functions that give a list context to everything on their right, eg. print, chmod, exec, and so on. Such functions are called &quot;list operators&quot; and appear as such in the precedence table in <a href="/5.6.1/perlop">perlop</a>.</p> <p>A common mistake is to write:</p> <pre><code>unlink $file || die &quot;snafu&quot;;</code></pre> <p>This gets interpreted as:</p> <pre><code>unlink ($file || die &quot;snafu&quot;);</code></pre> <p>To avoid this problem, either put in extra parentheses or use the super low precedence <code>or</code> operator:</p> <pre><code>(unlink $file) || die &quot;snafu&quot;; unlink $file or die &quot;snafu&quot;;</code></pre> <p>The &quot;English&quot; operators (<code>and</code>, <code>or</code>, <code>xor</code>, and <code>not</code>) deliberately have precedence lower than that of list operators for just such situations as the one above.</p> <p>Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making <code>-2**2</code> product a negative not a positive four. It is also right-associating, meaning that <code>2**3**2</code> is two raised to the ninth power, not eight squared.</p> <p>Although it has the same precedence as in C, Perl&#39;s <code>?:</code> operator produces an lvalue. This assigns $x to either $a or $b, depending on the trueness of $maybe:</p> <pre><code>($maybe ? $a : $b) = $x;</code></pre> <h2 id="How-do-I-declare/create-a-structure?"><a class="permalink" href="#How-do-I-declare/create-a-structure?">#</a><a id="How2"></a><a id="How-do-I-declare-create-a-structure"></a>How do I declare/create a structure?</h2> <p>In general, you don&#39;t &quot;declare&quot; a structure. Just use a (probably anonymous) hash reference. See <a href="/5.6.1/perlref">perlref</a> and <a href="/5.6.1/perldsc">perldsc</a> for details. Here&#39;s an example:</p> <pre><code>$person = {}; # new anonymous hash $person-&gt;{AGE} = 24; # set field AGE to 24 $person-&gt;{NAME} = &quot;Nat&quot;; # set field NAME to &quot;Nat&quot;</code></pre> <p>If you&#39;re looking for something a bit more rigorous, try <a href="/5.6.1/perltoot">perltoot</a>.</p> <h2 id="How-do-I-create-a-module?"><a class="permalink" href="#How-do-I-create-a-module?">#</a><a id="How3"></a><a id="How-do-I-create-a-module"></a>How do I create a module?</h2> <p>A module is a package that lives in a file of the same name. For example, the Hello::There module would live in Hello/There.pm. For details, read <a href="/5.6.1/perlmod">perlmod</a>. You&#39;ll also find <a href="/5.6.1/Exporter">Exporter</a> helpful. If you&#39;re writing a C or mixed-language module with both C and Perl, then you should study <a href="/5.6.1/perlxstut">perlxstut</a>.</p> <p>Here&#39;s a convenient template you might wish you use when starting your own module. Make sure to change the names appropriately.</p> <pre><code> package Some::Module; # assumes Some/Module.pm use strict; use warnings; BEGIN { use Exporter (); our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); ## set the version for version checking; uncomment to use ## $VERSION = 1.00; # if using RCS/CVS, this next line may be preferred, # but beware two-digit versions. $VERSION = do{my@r=q$Revision: 1.28 $=~/\d+/g;sprintf &#39;%d.&#39;.&#39;%02d&#39;x$#r,@r}; @ISA = qw(Exporter); @EXPORT = qw(&amp;func1 &amp;func2 &amp;func3); %EXPORT_TAGS = ( ); # eg: TAG =&gt; [ qw!name1 name2! ], # your exported package globals go here, # as well as any optionally exported functions @EXPORT_OK = qw($Var1 %Hashit); } our @EXPORT_OK; # exported package globals go here our $Var1; our %Hashit; # non-exported package globals go here our @more; our $stuff; # initialize package globals, first exported ones $Var1 = &#39;&#39;; %Hashit = (); # then the others (which are still accessible as $Some::Module::stuff) $stuff = &#39;&#39;; @more = (); # all file-scoped lexicals must be created before # the functions below that use them. # file-private lexicals go here my $priv_var = &#39;&#39;; my %secret_hash = (); # here&#39;s a file-private function as a closure, # callable as &amp;$priv_func; it cannot be prototyped. my $priv_func = sub { # stuff goes here. }; # make all your functions, whether exported or not; # remember to put something interesting in the {} stubs sub func1 {} # no prototype sub func2() {} # proto&#39;d void sub func3($$) {} # proto&#39;d to 2 scalars # this one isn&#39;t exported, but could be called! sub func4(\%) {} # proto&#39;d to 1 hash ref END { } # module clean-up code here (global destructor) 1; # modules must return true</code></pre> <p>The h2xs program will create stubs for all the important stuff for you:</p> <pre><code class="plaintext">% h2xs -XA -n My::Module</code></pre> <h2 id="How-do-I-create-a-class?"><a class="permalink" href="#How-do-I-create-a-class?">#</a><a id="How4"></a><a id="How-do-I-create-a-class"></a>How do I create a class?</h2> <p>See <a href="/5.6.1/perltoot">perltoot</a> for an introduction to classes and objects, as well as <a href="/5.6.1/perlobj">perlobj</a> and <a href="/5.6.1/perlbot">perlbot</a>.</p> <h2 id="How-can-I-tell-if-a-variable-is-tainted?"><a class="permalink" href="#How-can-I-tell-if-a-variable-is-tainted?">#</a><a id="How5"></a><a id="How-can-I-tell-if-a-variable-is-tainted"></a>How can I tell if a variable is tainted?</h2> <p>See <a href="/5.6.1/perlsec#Laundering-and-Detecting-Tainted-Data">&quot;Laundering and Detecting Tainted Data&quot; in perlsec</a>. Here&#39;s an example (which doesn&#39;t use any system calls, because the kill() is given no processes to signal):</p> <pre><code> sub is_tainted { return ! eval { join(&#39;&#39;,@_), kill 0; 1; }; }</code></pre> <p>This is not <code>-w</code> clean, however. There is no <code>-w</code> clean way to detect taintedness--take this as a hint that you should untaint all possibly-tainted data.</p> <h2 id="What&#39;s-a-closure?"><a class="permalink" href="#What&#39;s-a-closure?">#</a><a id="What2"></a><a id="Whats-a-closure"></a>What&#39;s a closure?</h2> <p>Closures are documented in <a href="/5.6.1/perlref">perlref</a>.</p> <p><i>Closure</i> is a computer science term with a precise but hard-to-explain meaning. Closures are implemented in Perl as anonymous subroutines with lasting references to lexical variables outside their own scopes. These lexicals magically refer to the variables that were around when the subroutine was defined (deep binding).</p> <p>Closures make sense in any programming language where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures: the Python language, for example. For more information on closures, check out any textbook on functional programming. Scheme is a language that not only supports but encourages closures.</p> <p>Here&#39;s a classic function-generating function:</p> <pre><code>sub add_function_generator { return sub { shift + shift }; } $add_sub = add_function_generator(); $sum = $add_sub-&gt;(4,5); # $sum is 9 now.</code></pre> <p>The closure works as a <i>function template</i> with some customization slots left out to be filled later. The anonymous subroutine returned by add_function_generator() isn&#39;t technically a closure because it refers to no lexicals outside its own scope.</p> <p>Contrast this with the following make_adder() function, in which the returned anonymous function contains a reference to a lexical variable outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created.</p> <pre><code>sub make_adder { my $addpiece = shift; return sub { shift + $addpiece }; } $f1 = make_adder(20); $f2 = make_adder(555);</code></pre> <p>Now <code>&amp;$f1($n)</code> is always 20 plus whatever $n you pass in, whereas <code>&amp;$f2($n)</code> is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around.</p> <p>Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function:</p> <pre><code>my $line; timeout( 30, sub { $line = &lt;STDIN&gt; } );</code></pre> <p>If the code to execute had been passed in as a string, <code>&#39;$line = &lt;STDIN&gt;&#39;</code>, there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller&#39;s scope.</p> <h2 id="What-is-variable-suicide-and-how-can-I-prevent-it?"><a class="permalink" href="#What-is-variable-suicide-and-how-can-I-prevent-it?">#</a><a id="What3"></a><a id="What-is-variable-suicide-and-how-can-I-prevent-it"></a>What is variable suicide and how can I prevent it?</h2> <p>Variable suicide is when you (temporarily or permanently) lose the value of a variable. It is caused by scoping through my() and local() interacting with either closures or aliased foreach() iterator variables and subroutine arguments. It used to be easy to inadvertently lose a variable&#39;s value this way, but now it&#39;s much harder. Take this code:</p> <pre><code>my $f = &quot;foo&quot;; sub T { while ($i++ &lt; 3) { my $f = $f; $f .= &quot;bar&quot;; print $f, &quot;\n&quot; } } T; print &quot;Finally $f\n&quot;;</code></pre> <p>The $f that has &quot;bar&quot; added to it three times should be a new <code>$f</code> (<code>my $f</code> should create a new local variable each time through the loop). It isn&#39;t, however. This was a bug, now fixed in the latest releases (tested against 5.004_05, 5.005_03, and 5.005_56).</p> <h2 id="How-can-I-pass/return-a-{Function,-FileHandle,-Array,-Hash,-Method,-Regex}?"><a class="permalink" href="#How-can-I-pass/return-a-%7BFunction,-FileHandle,-Array,-Hash,-Method,-Regex%7D?">#</a><a id="How6"></a><a id="How-can-I-pass-return-a-Function-FileHandle-Array-Hash-Method-Regex"></a>How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}?</h2> <p>With the exception of regexes, you need to pass references to these objects. See <a href="/5.6.1/perlsub#Pass-by-Reference">&quot;Pass by Reference&quot; in perlsub</a> for this particular question, and <a href="/5.6.1/perlref">perlref</a> for information on references.</p> <p>See ``Passing Regexes&#39;&#39;, below, for information on passing regular expressions.</p> <dl> <dt id="Passing-Variables-and-Functions"><a class="permalink" href="#Passing-Variables-and-Functions">#</a><a id="Passing"></a>Passing Variables and Functions</dt> <dd> <p>Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function:</p> <pre><code>func( \$some_scalar ); func( \@some_array ); func( [ 1 .. 10 ] ); func( \%some_hash ); func( { this =&gt; 10, that =&gt; 20 } ); func( \&amp;some_func ); func( sub { $_[0] ** $_[1] } );</code></pre> </dd> <dt id="Passing-Filehandles"><a class="permalink" href="#Passing-Filehandles">#</a><a id="Passing1"></a>Passing Filehandles</dt> <dd> <p>To pass filehandles to subroutines, use the <code>*FH</code> or <code>\*FH</code> notations. These are &quot;typeglobs&quot;--see <a href="/5.6.1/perldata#Typeglobs-and-Filehandles">&quot;Typeglobs and Filehandles&quot; in perldata</a> and especially <a href="/5.6.1/perlsub#Pass-by-Reference">&quot;Pass by Reference&quot; in perlsub</a> for more information.</p> <p>Here&#39;s an excerpt:</p> <p>If you&#39;re passing around filehandles, you could usually just use the bare typeglob, like *STDOUT, but typeglobs references would be better because they&#39;ll still work properly under <code>use strict &#39;refs&#39;</code>. For example:</p> <pre><code>splutter(\*STDOUT); sub splutter { my $fh = shift; print $fh &quot;her um well a hmmm\n&quot;; } $rec = get_rec(\*STDIN); sub get_rec { my $fh = shift; return scalar &lt;$fh&gt;; }</code></pre> <p>If you&#39;re planning on generating new filehandles, you could do this:</p> <pre><code>sub openit { my $path = shift; local *FH; return open (FH, $path) ? *FH : undef; } $fh = openit(&#39;&lt; /etc/motd&#39;); print &lt;$fh&gt;;</code></pre> </dd> <dt id="Passing-Regexes"><a class="permalink" href="#Passing-Regexes">#</a><a id="Passing2"></a>Passing Regexes</dt> <dd> <p>To pass regexes around, you&#39;ll need to be using a release of Perl sufficiently recent as to support the <code>qr//</code> construct, pass around strings and use an exception-trapping eval, or else be very, very clever.</p> <p>Here&#39;s an example of how to pass in a string to be regex compared using <code>qr//</code>:</p> <pre><code> sub compare($$) { my ($val1, $regex) = @_; my $retval = $val1 =~ /$regex/; return $retval; } $match = compare(&quot;old McDonald&quot;, qr/d.*D/i);</code></pre> <p>Notice how <code>qr//</code> allows flags at the end. That pattern was compiled at compile time, although it was executed later. The nifty <code>qr//</code> notation wasn&#39;t introduced until the 5.005 release. Before that, you had to approach this problem much less intuitively. For example, here it is again if you don&#39;t have <code>qr//</code>:</p> <pre><code> sub compare($$) { my ($val1, $regex) = @_; my $retval = eval { $val1 =~ /$regex/ }; die if $@; return $retval; } $match = compare(&quot;old McDonald&quot;, q/($?i)d.*D/);</code></pre> <p>Make sure you never say something like this:</p> <pre><code>return eval &quot;\$val =~ /$regex/&quot;; # WRONG</code></pre> <p>or someone can sneak shell escapes into the regex due to the double interpolation of the eval and the double-quoted string. For example:</p> <pre><code>$pattern_of_evil = &#39;danger ${ system(&quot;rm -rf * &amp;&quot;) } danger&#39;; eval &quot;\$string =~ /$pattern_of_evil/&quot;;</code></pre> <p>Those preferring to be very, very clever might see the O&#39;Reilly book, <i>Mastering Regular Expressions</i>, by Jeffrey Friedl. Page 273&#39;s Build_MatchMany_Function() is particularly interesting. A complete citation of this book is given in <a href="/5.6.1/perlfaq2">perlfaq2</a>.</p> </dd> <dt id="Passing-Methods"><a class="permalink" href="#Passing-Methods">#</a><a id="Passing3"></a>Passing Methods</dt> <dd> <p>To pass an object method into a subroutine, you can do this:</p> <pre><code>call_a_lot(10, $some_obj, &quot;methname&quot;) sub call_a_lot { my ($count, $widget, $trick) = @_; for (my $i = 0; $i &lt; $count; $i++) { $widget-&gt;$trick(); } }</code></pre> <p>Or, you can use a closure to bundle up the object, its method call, and arguments:</p> <pre><code>my $whatnot = sub { $some_obj-&gt;obfuscate(@args) }; func($whatnot); sub func { my $code = shift; &amp;$code(); }</code></pre> <p>You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution).</p> </dd> </dl> <h2 id="How-do-I-create-a-static-variable?"><a class="permalink" href="#How-do-I-create-a-static-variable?">#</a><a id="How7"></a><a id="How-do-I-create-a-static-variable"></a>How do I create a static variable?</h2> <p>As with most things in Perl, TMTOWTDI. What is a &quot;static variable&quot; in other languages could be either a function-private variable (visible only within a single function, retaining its value between calls to that function), or a file-private variable (visible only to functions within the file it was declared in) in Perl.</p> <p>Here&#39;s code to implement a function-private variable:</p> <pre><code>BEGIN { my $counter = 42; sub prev_counter { return --$counter } sub next_counter { return $counter++ } }</code></pre> <p>Now prev_counter() and next_counter() share a private variable $counter that was initialized at compile time.</p> <p>To declare a file-private variable, you&#39;ll still use a my(), putting the declaration at the outer scope level at the top of the file. Assume this is in file Pax.pm:</p> <pre><code>package Pax; my $started = scalar(localtime(time())); sub begun { return $started }</code></pre> <p>When <code>use Pax</code> or <code>require Pax</code> loads this module, the variable will be initialized. It won&#39;t get garbage-collected the way most variables going out of scope do, because the begun() function cares about it, but no one else can get it. It is not called $Pax::started because its scope is unrelated to the package. It&#39;s scoped to the file. You could conceivably have several packages in that same file all accessing the same private variable, but another file with the same package couldn&#39;t get to it.</p> <p>See <a href="/5.6.1/perlsub#Persistent-Private-Variables">&quot;Persistent Private Variables&quot; in perlsub</a> for details.</p> <h2 id="What&#39;s-the-difference-between-dynamic-and-lexical-(static)-scoping?-Between-local()-and-my()?"><a class="permalink" href="#What&#39;s-the-difference-between-dynamic-and-lexical-(static)-scoping?-Between-local()-and-my()?">#</a><a id="What4"></a><a id="Whats-the-difference-between-dynamic-and-lexical-static-scoping-Between-local-and-my"></a>What&#39;s the difference between dynamic and lexical (static) scoping? Between local() and my()?</h2> <p><code>local($x)</code> saves away the old value of the global variable <code>$x</code> and assigns a new value for the duration of the subroutine <i>which is visible in other functions called from that subroutine</i>. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables.</p> <p><code>my($x)</code> creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.</p> <p>For instance:</p> <pre><code> sub visible { print &quot;var has value $var\n&quot;; } sub dynamic { local $var = &#39;local&#39;; # new temporary value for the still-global visible(); # variable called $var } sub lexical { my $var = &#39;private&#39;; # new private variable, $var visible(); # (invisible outside of sub scope) } $var = &#39;global&#39;; visible(); # prints global dynamic(); # prints local lexical(); # prints global</code></pre> <p>Notice how at no point does the value &quot;private&quot; get printed. That&#39;s because $var only has that value within the block of the lexical() function, and it is hidden from called subroutine.</p> <p>In summary, local() doesn&#39;t make what you think of as private, local variables. It gives a global variable a temporary value. my() is what you&#39;re looking for if you want private variables.</p> <p>See <a href="/5.6.1/perlsub#Private-Variables-via-my()">&quot;Private Variables via my()&quot; in perlsub</a> and <a href="/5.6.1/perlsub#Temporary-Values-via-local()">&quot;Temporary Values via local()&quot; in perlsub</a> for excruciating details.</p> <h2 id="How-can-I-access-a-dynamic-variable-while-a-similarly-named-lexical-is-in-scope?"><a class="permalink" href="#How-can-I-access-a-dynamic-variable-while-a-similarly-named-lexical-is-in-scope?">#</a><a id="How8"></a><a id="How-can-I-access-a-dynamic-variable-while-a-similarly-named-lexical-is-in-scope"></a>How can I access a dynamic variable while a similarly named lexical is in scope?</h2> <p>You can do this via symbolic references, provided you haven&#39;t set <code>use strict &quot;refs&quot;</code>. So instead of $var, use <code>${&#39;var&#39;}</code>.</p> <pre><code>local $var = &quot;global&quot;; my $var = &quot;lexical&quot;; print &quot;lexical is $var\n&quot;; no strict &#39;refs&#39;; print &quot;global is ${&#39;var&#39;}\n&quot;;</code></pre> <p>If you know your package, you can just mention it explicitly, as in $Some_Pack::var. Note that the notation $::var is <i>not</i> the dynamic $var in the current package, but rather the one in the <code>main</code> package, as though you had written $main::var. Specifying the package directly makes you hard-code its name, but it executes faster and avoids running afoul of <code>use strict &quot;refs&quot;</code>.</p> <h2 id="What&#39;s-the-difference-between-deep-and-shallow-binding?"><a class="permalink" href="#What&#39;s-the-difference-between-deep-and-shallow-binding?">#</a><a id="What5"></a><a id="Whats-the-difference-between-deep-and-shallow-binding"></a>What&#39;s the difference between deep and shallow binding?</h2> <p>In deep binding, lexical variables mentioned in anonymous subroutines are the same ones that were in scope when the subroutine was created. In shallow binding, they are whichever variables with the same names happen to be in scope when the subroutine is called. Perl always uses deep binding of lexical variables (i.e., those created with my()). However, dynamic variables (aka global, local, or package variables) are effectively shallowly bound. Consider this just one more reason not to use them. See the answer to <a href="#What%27s-a-closure%3F">&quot;What&#39;s a closure?&quot;</a>.</p> <h2 id="Why-doesn&#39;t-&quot;my($foo)-=-&lt;FILE&gt;;&quot;-work-right?"><a class="permalink" href="#Why-doesn&#39;t-%22my($foo)-=-%3CFILE%3E;%22-work-right?">#</a><a id="Why1"></a><a id="Why-doesnt-my-foo-FILE-work-right"></a>Why doesn&#39;t &quot;my($foo) = &lt;FILE&gt;;&quot; work right?</h2> <p><code>my()</code> and <code>local()</code> give list context to the right hand side of <code>=</code>. The &lt;FH&gt; read operation, like so many of Perl&#39;s functions and operators, can tell which context it was called in and behaves appropriately. In general, the scalar() function can help. This function does nothing to the data itself (contrary to popular myth) but rather tells its argument to behave in whatever its scalar fashion is. If that function doesn&#39;t have a defined scalar behavior, this of course doesn&#39;t help you (such as with sort()).</p> <p>To enforce scalar context in this particular case, however, you need merely omit the parentheses:</p> <pre><code>local($foo) = &lt;FILE&gt;; # WRONG local($foo) = scalar(&lt;FILE&gt;); # ok local $foo = &lt;FILE&gt;; # right</code></pre> <p>You should probably be using lexical variables anyway, although the issue is the same here:</p> <pre><code>my($foo) = &lt;FILE&gt;; # WRONG my $foo = &lt;FILE&gt;; # right</code></pre> <h2 id="How-do-I-redefine-a-builtin-function,-operator,-or-method?"><a class="permalink" href="#How-do-I-redefine-a-builtin-function,-operator,-or-method?">#</a><a id="How9"></a><a id="How-do-I-redefine-a-builtin-function-operator-or-method"></a>How do I redefine a builtin function, operator, or method?</h2> <p>Why do you want to do that? :-)</p> <p>If you want to override a predefined function, such as open(), then you&#39;ll have to import the new definition from a different module. See <a href="/5.6.1/perlsub#Overriding-Built-in-Functions">&quot;Overriding Built-in Functions&quot; in perlsub</a>. There&#39;s also an example in <a href="/5.6.1/perltoot#Class%3A%3ATemplate">&quot;Class::Template&quot; in perltoot</a>.</p> <p>If you want to overload a Perl operator, such as <code>+</code> or <code>**</code>, then you&#39;ll want to use the <code>use overload</code> pragma, documented in <a href="/5.6.1/overload">overload</a>.</p> <p>If you&#39;re talking about obscuring method calls in parent classes, see <a href="/5.6.1/perltoot#Overridden-Methods">&quot;Overridden Methods&quot; in perltoot</a>.</p> <h2 id="What&#39;s-the-difference-between-calling-a-function-as-&amp;foo-and-foo()?"><a class="permalink" href="#What&#39;s-the-difference-between-calling-a-function-as-&amp;foo-and-foo()?">#</a><a id="What6"></a><a id="Whats-the-difference-between-calling-a-function-as-foo-and-foo"></a>What&#39;s the difference between calling a function as &amp;foo and foo()?</h2> <p>When you call a function as <code>&amp;foo</code>, you allow that function access to your current @_ values, and you bypass prototypes. The function doesn&#39;t get an empty @_--it gets yours! While not strictly speaking a bug (it&#39;s documented that way in <a href="/5.6.1/perlsub">perlsub</a>), it would be hard to consider this a feature in most cases.</p> <p>When you call your function as <code>&amp;foo()</code>, then you <i>do</i> get a new @_, but prototyping is still circumvented.</p> <p>Normally, you want to call a function using <code>foo()</code>. You may only omit the parentheses if the function is already known to the compiler because it already saw the definition (<code>use</code> but not <code>require</code>), or via a forward reference or <code>use subs</code> declaration. Even in this case, you get a clean @_ without any of the old values leaking through where they don&#39;t belong.</p> <h2 id="How-do-I-create-a-switch-or-case-statement?"><a class="permalink" href="#How-do-I-create-a-switch-or-case-statement?">#</a><a id="How10"></a><a id="How-do-I-create-a-switch-or-case-statement"></a>How do I create a switch or case statement?</h2> <p>This is explained in more depth in the <a href="/5.6.1/perlsyn">perlsyn</a>. Briefly, there&#39;s no official case statement, because of the variety of tests possible in Perl (numeric comparison, string comparison, glob comparison, regex matching, overloaded comparisons, ...). Larry couldn&#39;t decide how best to do this, so he left it out, even though it&#39;s been on the wish list since perl1.</p> <p>The general answer is to write a construct like this:</p> <pre><code> for ($variable_to_test) { if (/pat1/) { } # do something elsif (/pat2/) { } # do something else elsif (/pat3/) { } # do something else else { } # default } </code></pre> <p>Here&#39;s a simple example of a switch based on pattern matching, this time lined up in a way to make it look more like a switch statement. We&#39;ll do a multi-way conditional based on the type of reference stored in $whatchamacallit:</p> <pre><code> SWITCH: for (ref $whatchamacallit) { /^$/ &amp;&amp; die &quot;not a reference&quot;; /SCALAR/ &amp;&amp; do { print_scalar($$ref); last SWITCH; }; /ARRAY/ &amp;&amp; do { print_array(@$ref); last SWITCH; }; /HASH/ &amp;&amp; do { print_hash(%$ref); last SWITCH; }; /CODE/ &amp;&amp; do { warn &quot;can&#39;t print function ref&quot;; last SWITCH; }; # DEFAULT warn &quot;User defined type skipped&quot;; }</code></pre> <p>See <code>perlsyn/&quot;Basic BLOCKs and Switch Statements&quot;</code> for many other examples in this style.</p> <p>Sometimes you should change the positions of the constant and the variable. For example, let&#39;s say you wanted to test which of many answers you were given, but in a case-insensitive way that also allows abbreviations. You can use the following technique if the strings all start with different characters or if you want to arrange the matches so that one takes precedence over another, as <code>&quot;SEND&quot;</code> has precedence over <code>&quot;STOP&quot;</code> here:</p> <pre><code>chomp($answer = &lt;&gt;); if (&quot;SEND&quot; =~ /^\Q$answer/i) { print &quot;Action is send\n&quot; } elsif (&quot;STOP&quot; =~ /^\Q$answer/i) { print &quot;Action is stop\n&quot; } elsif (&quot;ABORT&quot; =~ /^\Q$answer/i) { print &quot;Action is abort\n&quot; } elsif (&quot;LIST&quot; =~ /^\Q$answer/i) { print &quot;Action is list\n&quot; } elsif (&quot;EDIT&quot; =~ /^\Q$answer/i) { print &quot;Action is edit\n&quot; }</code></pre> <p>A totally different approach is to create a hash of function references.</p> <pre><code>my %commands = ( &quot;happy&quot; =&gt; \&amp;joy, &quot;sad&quot;, =&gt; \&amp;sullen, &quot;done&quot; =&gt; sub { die &quot;See ya!&quot; }, &quot;mad&quot; =&gt; \&amp;angry, ); print &quot;How are you? &quot;; chomp($string = &lt;STDIN&gt;); if ($commands{$string}) { $commands{$string}-&gt;(); } else { print &quot;No such command: $string\n&quot;; } </code></pre> <h2 id="How-can-I-catch-accesses-to-undefined-variables/functions/methods?"><a class="permalink" href="#How-can-I-catch-accesses-to-undefined-variables/functions/methods?">#</a><a id="How11"></a><a id="How-can-I-catch-accesses-to-undefined-variables-functions-methods"></a>How can I catch accesses to undefined variables/functions/methods?</h2> <p>The AUTOLOAD method, discussed in <a href="/5.6.1/perlsub#Autoloading">&quot;Autoloading&quot; in perlsub</a> and <a href="/5.6.1/perltoot#AUTOLOAD%3A-Proxy-Methods">&quot;AUTOLOAD: Proxy Methods&quot; in perltoot</a>, lets you capture calls to undefined functions and methods.</p> <p>When it comes to undefined variables that would trigger a warning under <code>-w</code>, you can use a handler to trap the pseudo-signal <code>__WARN__</code> like this:</p> <pre><code> $SIG{__WARN__} = sub { for ( $_[0] ) { # voici un switch statement /Use of uninitialized value/ &amp;&amp; do { # promote warning to a fatal die $_; }; # other warning cases to catch could go here; warn $_; } };</code></pre> <h2 id="Why-can&#39;t-a-method-included-in-this-same-file-be-found?"><a class="permalink" href="#Why-can&#39;t-a-method-included-in-this-same-file-be-found?">#</a><a id="Why2"></a><a id="Why-cant-a-method-included-in-this-same-file-be-found"></a>Why can&#39;t a method included in this same file be found?</h2> <p>Some possible reasons: your inheritance is getting confused, you&#39;ve misspelled the method name, or the object is of the wrong type. Check out <a href="/5.6.1/perltoot">perltoot</a> for details about any of the above cases. You may also use <code>print ref($object)</code> to find out the class <code>$object</code> was blessed into.</p> <p>Another possible reason for problems is because you&#39;ve used the indirect object syntax (eg, <code>find Guru &quot;Samy&quot;</code>) on a class name before Perl has seen that such a package exists. It&#39;s wisest to make sure your packages are all defined before you start using them, which will be taken care of if you use the <code>use</code> statement instead of <code>require</code>. If not, make sure to use arrow notation (eg., <code>Guru-&gt;find(&quot;Samy&quot;)</code>) instead. Object notation is explained in <a href="/5.6.1/perlobj">perlobj</a>.</p> <p>Make sure to read about creating modules in <a href="/5.6.1/perlmod">perlmod</a> and the perils of indirect objects in <a href="/5.6.1/perlobj#WARNING">&quot;WARNING&quot; in perlobj</a>.</p> <h2 id="How-can-I-find-out-my-current-package?"><a class="permalink" href="#How-can-I-find-out-my-current-package?">#</a><a id="How12"></a><a id="How-can-I-find-out-my-current-package"></a>How can I find out my current package?</h2> <p>If you&#39;re just a random program, you can do this to find out what the currently compiled package is:</p> <pre><code>my $packname = __PACKAGE__;</code></pre> <p>But, if you&#39;re a method and you want to print an error message that includes the kind of object you were called on (which is not necessarily the same as the one in which you were compiled):</p> <pre><code> sub amethod { my $self = shift; my $class = ref($self) || $self; warn &quot;called me from a $class object&quot;; }</code></pre> <h2 id="How-can-I-comment-out-a-large-block-of-perl-code?"><a class="permalink" href="#How-can-I-comment-out-a-large-block-of-perl-code?">#</a><a id="How13"></a><a id="How-can-I-comment-out-a-large-block-of-perl-code"></a>How can I comment out a large block of perl code?</h2> <p>Use embedded POD to discard it:</p> <pre><code class="plaintext"># program is here =for nobody This paragraph is commented out # program continues =begin comment text all of this stuff here will be ignored by everyone =end comment text =cut</code></pre> <p>This can&#39;t go just anywhere. You have to put a pod directive where the parser is expecting a new statement, not just in the middle of an expression or some other arbitrary yacc grammar production.</p> <h2 id="How-do-I-clear-a-package?"><a class="permalink" href="#How-do-I-clear-a-package?">#</a><a id="How14"></a><a id="How-do-I-clear-a-package"></a>How do I clear a package?</h2> <p>Use this code, provided by Mark-Jason Dominus:</p> <pre><code> sub scrub_package { no strict &#39;refs&#39;; my $pack = shift; die &quot;Shouldn&#39;t delete main package&quot; if $pack eq &quot;&quot; || $pack eq &quot;main&quot;; my $stash = *{$pack . &#39;::&#39;}{HASH}; my $name; foreach $name (keys %$stash) { my $fullname = $pack . &#39;::&#39; . $name; # Get rid of everything with that name. undef $$fullname; undef @$fullname; undef %$fullname; undef &amp;$fullname; undef *$fullname; } }</code></pre> <p>Or, if you&#39;re using a recent release of Perl, you can just use the Symbol::delete_package() function instead.</p> <h2 id="How-can-I-use-a-variable-as-a-variable-name?"><a class="permalink" href="#How-can-I-use-a-variable-as-a-variable-name?">#</a><a id="How15"></a><a id="How-can-I-use-a-variable-as-a-variable-name"></a>How can I use a variable as a variable name?</h2> <p>Beginners often think they want to have a variable contain the name of a variable.</p> <pre><code>$fred = 23; $varname = &quot;fred&quot;; ++$$varname; # $fred now 24</code></pre> <p>This works <i>sometimes</i>, but it is a very bad idea for two reasons.</p> <p>The first reason is that this technique <i>only works on global variables</i>. That means that if $fred is a lexical variable created with my() in the above example, the code wouldn&#39;t work at all: you&#39;d accidentally access the global and skip right over the private lexical altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code.</p> <p>Symbolic references are forbidden under the <code>use strict</code> pragma. They are not true references and consequently are not reference counted or garbage collected.</p> <p>The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package&#39;s symbol-table hash (like <code>%main::</code>) instead of a user-defined hash. The solution is to use your own hash or a real reference instead.</p> <pre><code>$fred = 23; $varname = &quot;fred&quot;; $USER_VARS{$varname}++; # not $$varname++</code></pre> <p>There we&#39;re using the %USER_VARS hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl program&#39;s variables. This is also a bad idea because it conflates the program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program&#39;s own variables:</p> <pre><code>$str = &#39;this has a $fred and $barney in it&#39;; $str =~ s/(\$\w+)/$1/eeg; # need double eval</code></pre> <p>it would be better to keep a hash around like %USER_VARS and have variable references actually refer to entries in that hash:</p> <pre><code>$str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all</code></pre> <p>That&#39;s faster, cleaner, and safer than the previous approach. Of course, you don&#39;t need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc.</p> <pre><code>$str = &#39;this has a %fred% and %barney% in it&#39;; $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all</code></pre> <p>Another reason that folks sometimes think they want a variable to contain the name of a variable is because they don&#39;t know how to build proper data structures using hashes. For example, let&#39;s say they wanted two hashes in their program: %fred and %barney, and that they wanted to use another scalar variable to refer to those by name.</p> <pre><code>$name = &quot;fred&quot;; $$name{WIFE} = &quot;wilma&quot;; # set %fred $name = &quot;barney&quot;; $$name{WIFE} = &quot;betty&quot;; # set %barney</code></pre> <p>This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write:</p> <pre><code>$folks{&quot;fred&quot;}{WIFE} = &quot;wilma&quot;; $folks{&quot;barney&quot;}{WIFE} = &quot;betty&quot;;</code></pre> <p>And just use a multilevel hash to start with.</p> <p>The only times that you absolutely <i>must</i> use symbolic references are when you really must refer to the symbol table. This may be because it&#39;s something that can&#39;t take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution.</p> <p>In those cases, you would turn off <code>strict &#39;refs&#39;</code> temporarily so you can play around with the symbol table. For example:</p> <pre><code>@colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { no strict &#39;refs&#39;; # renege for the block *$name = sub { &quot;&lt;FONT COLOR=&#39;$name&#39;&gt;@_&lt;/FONT&gt;&quot; }; } </code></pre> <p>All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once.</p> <p>So, sometimes you might want to use symbolic references to directly manipulate the symbol table. This doesn&#39;t matter for formats, handles, and subroutines, because they are always global--you can&#39;t use my() on them. For scalars, arrays, and hashes, though--and usually for subroutines-- you probably only want to use hard references.</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-1999 Tom Christiansen and Nathan Torkington. All rights reserved.</p> <p>When included as part of the Standard Version of Perl, or as part of its complete documentation whether printed or otherwise, this work may be distributed only under the terms of Perl&#39;s Artistic License. Any distribution of this file or derivatives thereof <i>outside</i> of that package require that special arrangements be made with copyright holder.</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="/js/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>

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