CINXE.COM

perlintro -- a brief introduction and overview of Perl - 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>perlintro -- a brief introduction and overview of Perl - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/perlintro"> <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.8.4</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/perlintro">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0/perlintro">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.2/perlintro">5.38.2</a> <a class="dropdown-item" href="/5.38.1/perlintro">5.38.1</a> <a class="dropdown-item" href="/5.38.0/perlintro">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/perlintro">5.36.3</a> <a class="dropdown-item" href="/5.36.2/perlintro">5.36.2</a> <a class="dropdown-item" href="/5.36.1/perlintro">5.36.1</a> <a class="dropdown-item" href="/5.36.0/perlintro">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/perlintro">5.34.3</a> <a class="dropdown-item" href="/5.34.2/perlintro">5.34.2</a> <a class="dropdown-item" href="/5.34.1/perlintro">5.34.1</a> <a class="dropdown-item" href="/5.34.0/perlintro">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/perlintro">5.32.1</a> <a class="dropdown-item" href="/5.32.0/perlintro">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/perlintro">5.30.3</a> <a class="dropdown-item" href="/5.30.2/perlintro">5.30.2</a> <a class="dropdown-item" href="/5.30.1/perlintro">5.30.1</a> <a class="dropdown-item" href="/5.30.0/perlintro">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/perlintro">5.28.3</a> <a class="dropdown-item" href="/5.28.2/perlintro">5.28.2</a> <a class="dropdown-item" href="/5.28.1/perlintro">5.28.1</a> <a class="dropdown-item" href="/5.28.0/perlintro">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/perlintro">5.26.3</a> <a class="dropdown-item" href="/5.26.2/perlintro">5.26.2</a> <a class="dropdown-item" href="/5.26.1/perlintro">5.26.1</a> <a class="dropdown-item" href="/5.26.0/perlintro">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/perlintro">5.24.4</a> <a class="dropdown-item" href="/5.24.3/perlintro">5.24.3</a> <a class="dropdown-item" href="/5.24.2/perlintro">5.24.2</a> <a class="dropdown-item" href="/5.24.1/perlintro">5.24.1</a> <a class="dropdown-item" href="/5.24.0/perlintro">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/perlintro">5.22.4</a> <a class="dropdown-item" href="/5.22.3/perlintro">5.22.3</a> <a class="dropdown-item" href="/5.22.2/perlintro">5.22.2</a> <a class="dropdown-item" href="/5.22.1/perlintro">5.22.1</a> <a class="dropdown-item" href="/5.22.0/perlintro">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/perlintro">5.20.3</a> <a class="dropdown-item" href="/5.20.2/perlintro">5.20.2</a> <a class="dropdown-item" href="/5.20.1/perlintro">5.20.1</a> <a class="dropdown-item" href="/5.20.0/perlintro">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/perlintro">5.18.4</a> <a class="dropdown-item" href="/5.18.3/perlintro">5.18.3</a> <a class="dropdown-item" href="/5.18.2/perlintro">5.18.2</a> <a class="dropdown-item" href="/5.18.1/perlintro">5.18.1</a> <a class="dropdown-item" href="/5.18.0/perlintro">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/perlintro">5.16.3</a> <a class="dropdown-item" href="/5.16.2/perlintro">5.16.2</a> <a class="dropdown-item" href="/5.16.1/perlintro">5.16.1</a> <a class="dropdown-item" href="/5.16.0/perlintro">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/perlintro">5.14.4</a> <a class="dropdown-item" href="/5.14.3/perlintro">5.14.3</a> <a class="dropdown-item" href="/5.14.2/perlintro">5.14.2</a> <a class="dropdown-item" href="/5.14.1/perlintro">5.14.1</a> <a class="dropdown-item" href="/5.14.0/perlintro">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/perlintro">5.12.5</a> <a class="dropdown-item" href="/5.12.4/perlintro">5.12.4</a> <a class="dropdown-item" href="/5.12.3/perlintro">5.12.3</a> <a class="dropdown-item" href="/5.12.2/perlintro">5.12.2</a> <a class="dropdown-item" href="/5.12.1/perlintro">5.12.1</a> <a class="dropdown-item" href="/5.12.0/perlintro">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/perlintro">5.10.1</a> <a class="dropdown-item" href="/5.10.0/perlintro">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/perlintro">5.8.9</a> <a class="dropdown-item" href="/5.8.8/perlintro">5.8.8</a> <a class="dropdown-item" href="/5.8.7/perlintro">5.8.7</a> <a class="dropdown-item" href="/5.8.6/perlintro">5.8.6</a> <a class="dropdown-item" href="/5.8.5/perlintro">5.8.5</a> <a class="dropdown-item active" href="/5.8.4/perlintro">5.8.4</a> <a class="dropdown-item" href="/5.8.3/perlintro">5.8.3</a> <a class="dropdown-item" href="/5.8.2/perlintro">5.8.2</a> <a class="dropdown-item" href="/5.8.1/perlintro">5.8.1</a> <a class="dropdown-item" href="/5.8.0/perlintro">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/perlintro">5.6.2</a> <a class="dropdown-item" href="/5.6.1/perlintro">5.6.1</a> <a class="dropdown-item" href="/5.6.0/perlintro">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/perlintro">5.005_04</a> <a class="dropdown-item" href="/5.005_03/perlintro">5.005_03</a> <a class="dropdown-item" href="/5.005_02/perlintro">5.005_02</a> <a class="dropdown-item" href="/5.005_01/perlintro">5.005_01</a> <a class="dropdown-item" href="/5.005/perlintro">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/perlintro">blead</a> <a class="dropdown-item" href="/5.41.6/perlintro">5.41.6</a> <a class="dropdown-item" href="/5.41.5/perlintro">5.41.5</a> <a class="dropdown-item" href="/5.41.4/perlintro">5.41.4</a> <a class="dropdown-item" href="/5.41.3/perlintro">5.41.3</a> <a class="dropdown-item" href="/5.41.2/perlintro">5.41.2</a> <a class="dropdown-item" href="/5.41.1/perlintro">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0-RC2/perlintro">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/perlintro">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/perlintro">5.39.10</a> <a class="dropdown-item" href="/5.39.9/perlintro">5.39.9</a> <a class="dropdown-item" href="/5.39.8/perlintro">5.39.8</a> <a class="dropdown-item" href="/5.39.7/perlintro">5.39.7</a> <a class="dropdown-item" href="/5.39.6/perlintro">5.39.6</a> <a class="dropdown-item" href="/5.39.5/perlintro">5.39.5</a> <a class="dropdown-item" href="/5.39.4/perlintro">5.39.4</a> <a class="dropdown-item" href="/5.39.3/perlintro">5.39.3</a> <a class="dropdown-item" href="/5.39.2/perlintro">5.39.2</a> <a class="dropdown-item" href="/5.39.1/perlintro">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.8.4/perl">Perl</a> <a class="dropdown-item" href="/5.8.4/perlintro">Intro</a> <a class="dropdown-item" href="/5.8.4/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/5.8.4/perlfaq">FAQs</a> <a class="dropdown-item" href="/5.8.4/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.4/perlop">Operators</a> <a class="dropdown-item" href="/5.8.4/functions">Functions</a> <a class="dropdown-item" href="/5.8.4/variables">Variables</a> <a class="dropdown-item" href="/5.8.4/modules">Modules</a> <a class="dropdown-item" href="/5.8.4/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.4/perldelta">Release Notes</a> <a class="dropdown-item" href="/5.8.4/perlcommunity">Community</a> <a class="dropdown-item" href="/5.8.4/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.8.4/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.8.4/perlintro">perlintro</a> <div id="more"> (<a href="/5.8.4/perlintro.txt">source</a>, <a href="https://metacpan.org/pod/perlintro">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl 5.8.4. <a href="/perlintro">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="#What-is-Perl?">What is Perl?</a> </li> <li> <a class="text-decoration-none" href="#Running-Perl-programs">Running Perl programs</a> </li> <li> <a class="text-decoration-none" href="#Basic-syntax-overview">Basic syntax overview</a> </li> <li> <a class="text-decoration-none" href="#Perl-variable-types">Perl variable types</a> </li> <li> <a class="text-decoration-none" href="#Variable-scoping">Variable scoping</a> </li> <li> <a class="text-decoration-none" href="#Conditional-and-looping-constructs">Conditional and looping constructs</a> </li> <li> <a class="text-decoration-none" href="#Builtin-operators-and-functions">Builtin operators and functions</a> </li> <li> <a class="text-decoration-none" href="#Files-and-I/O">Files and I/O</a> </li> <li> <a class="text-decoration-none" href="#Regular-expressions">Regular expressions</a> </li> <li> <a class="text-decoration-none" href="#Writing-subroutines">Writing subroutines</a> </li> <li> <a class="text-decoration-none" href="#OO-Perl">OO Perl</a> </li> <li> <a class="text-decoration-none" href="#Using-Perl-modules">Using Perl modules</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#AUTHOR">AUTHOR</a> </li> </ul> <h1 id="NAME"><a class="permalink" href="#NAME">#</a>NAME</h1> <p>perlintro -- a brief introduction and overview of Perl</p> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>This document is intended to give you a quick overview of the Perl programming language, along with pointers to further documentation. It is intended as a &quot;bootstrap&quot; guide for those who are new to the language, and provides just enough information for you to be able to read other peoples&#39; Perl and understand roughly what it&#39;s doing, or write your own simple scripts.</p> <p>This introductory document does not aim to be complete. It does not even aim to be entirely accurate. In some cases perfection has been sacrificed in the goal of getting the general idea across. You are <i>strongly</i> advised to follow this introduction with more information from the full Perl manual, the table of contents to which can be found in <a href="/5.8.4/perltoc">perltoc</a>.</p> <p>Throughout this document you&#39;ll see references to other parts of the Perl documentation. You can read that documentation using the <code>perldoc</code> command or whatever method you&#39;re using to read this document.</p> <h2 id="What-is-Perl?"><a class="permalink" href="#What-is-Perl?">#</a><a id="What"></a><a id="What-is-Perl"></a>What is Perl?</h2> <p>Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more.</p> <p>The language is intended to be practical (easy to use, efficient, complete) rather than beautiful (tiny, elegant, minimal). Its major features are that it&#39;s easy to use, supports both procedural and object-oriented (OO) programming, has powerful built-in support for text processing, and has one of the world&#39;s most impressive collections of third-party modules.</p> <p>Different definitions of Perl are given in <a href="/5.8.4/perl">perl</a>, <a href="/5.8.4/perlfaq1">perlfaq1</a> and no doubt other places. From this we can determine that Perl is different things to different people, but that lots of people think it&#39;s at least worth writing about.</p> <h2 id="Running-Perl-programs"><a class="permalink" href="#Running-Perl-programs">#</a><a id="Running"></a>Running Perl programs</h2> <p>To run a Perl program from the Unix command line:</p> <pre><code class="plaintext">perl progname.pl</code></pre> <p>Alternatively, put this as the first line of your script:</p> <pre><code class="plaintext">#!/usr/bin/env perl</code></pre> <p>... and run the script as <code>/path/to/script.pl</code>. Of course, it&#39;ll need to be executable first, so <code>chmod 755 script.pl</code> (under Unix).</p> <p>For more information, including instructions for other platforms such as Windows and Mac OS, read <a href="/5.8.4/perlrun">perlrun</a>.</p> <h2 id="Basic-syntax-overview"><a class="permalink" href="#Basic-syntax-overview">#</a><a id="Basic"></a>Basic syntax overview</h2> <p>A Perl script or program consists of one or more statements. These statements are simply written in the script in a straightforward fashion. There is no need to have a <code>main()</code> function or anything of that kind.</p> <p>Perl statements end in a semi-colon:</p> <pre><code>print &quot;Hello, world&quot;;</code></pre> <p>Comments start with a hash symbol and run to the end of the line</p> <pre><code class="plaintext"># This is a comment</code></pre> <p>Whitespace is irrelevant:</p> <pre><code>print &quot;Hello, world&quot; ;</code></pre> <p>... except inside quoted strings:</p> <pre><code># this would print with a linebreak in the middle print &quot;Hello world&quot;;</code></pre> <p>Double quotes or single quotes may be used around literal strings:</p> <pre><code>print &quot;Hello, world&quot;; print &#39;Hello, world&#39;;</code></pre> <p>However, only double quotes &quot;interpolate&quot; variables and special characters such as newlines (<code>\n</code>):</p> <pre><code>print &quot;Hello, $name\n&quot;; # works fine print &#39;Hello, $name\n&#39;; # prints $name\n literally</code></pre> <p>Numbers don&#39;t need quotes around them:</p> <pre><code>print 42;</code></pre> <p>You can use parentheses for functions&#39; arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence.</p> <pre><code>print(&quot;Hello, world\n&quot;); print &quot;Hello, world\n&quot;;</code></pre> <p>More detailed information about Perl syntax can be found in <a href="/5.8.4/perlsyn">perlsyn</a>.</p> <h2 id="Perl-variable-types"><a class="permalink" href="#Perl-variable-types">#</a><a id="Perl"></a>Perl variable types</h2> <p>Perl has three main variable types: scalars, arrays, and hashes.</p> <dl> <dt id="Scalars"><a class="permalink" href="#Scalars">#</a>Scalars</dt> <dd> <p>A scalar represents a single value:</p> <pre><code>my $animal = &quot;camel&quot;; my $answer = 42;</code></pre> <p>Scalar values can be strings, integers or floating point numbers, and Perl will automatically convert between them as required. There is no need to pre-declare your variable types.</p> <p>Scalar values can be used in various ways:</p> <pre><code>print $animal; print &quot;The animal is $animal\n&quot;; print &quot;The square of $answer is &quot;, $answer * $answer, &quot;\n&quot;;</code></pre> <p>There are a number of &quot;magic&quot; scalars with names that look like punctuation or line noise. These special variables are used for all kinds of purposes, and are documented in <a href="/5.8.4/perlvar">perlvar</a>. The only one you need to know about for now is <code>$_</code> which is the &quot;default variable&quot;. It&#39;s used as the default argument to a number of functions in Perl, and it&#39;s set implicitly by certain looping constructs.</p> <pre><code>print; # prints contents of $_ by default</code></pre> </dd> <dt id="Arrays"><a class="permalink" href="#Arrays">#</a>Arrays</dt> <dd> <p>An array represents a list of values:</p> <pre><code>my @animals = (&quot;camel&quot;, &quot;llama&quot;, &quot;owl&quot;); my @numbers = (23, 42, 69); my @mixed = (&quot;camel&quot;, 42, 1.23);</code></pre> <p>Arrays are zero-indexed. Here&#39;s how you get at elements in an array:</p> <pre><code>print $animals[0]; # prints &quot;camel&quot; print $animals[1]; # prints &quot;llama&quot;</code></pre> <p>The special variable <code>$#array</code> tells you the index of the last element of an array:</p> <pre><code>print $mixed[$#mixed]; # last element, prints 1.23</code></pre> <p>You might be tempted to use <code>$#array + 1</code> to tell you how many items there are in an array. Don&#39;t bother. As it happens, using <code>@array</code> where Perl expects to find a scalar value (&quot;in scalar context&quot;) will give you the number of elements in the array:</p> <pre><code>if (@animals &lt; 5) { ... }</code></pre> <p>The elements we&#39;re getting from the array start with a <code>$</code> because we&#39;re getting just a single value out of the array -- you ask for a scalar, you get a scalar.</p> <p>To get multiple values from an array:</p> <pre><code>@animals[0,1]; # gives (&quot;camel&quot;, &quot;llama&quot;); @animals[0..2]; # gives (&quot;camel&quot;, &quot;llama&quot;, &quot;owl&quot;); @animals[1..$#animals]; # gives all except the first element</code></pre> <p>This is called an &quot;array slice&quot;.</p> <p>You can do various useful things to lists:</p> <pre><code>my @sorted = sort @animals; my @backwards = reverse @numbers;</code></pre> <p>There are a couple of special arrays too, such as <code>@ARGV</code> (the command line arguments to your script) and <code>@_</code> (the arguments passed to a subroutine). These are documented in <a href="/5.8.4/perlvar">perlvar</a>.</p> </dd> <dt id="Hashes"><a class="permalink" href="#Hashes">#</a>Hashes</dt> <dd> <p>A hash represents a set of key/value pairs:</p> <pre><code>my %fruit_color = (&quot;apple&quot;, &quot;red&quot;, &quot;banana&quot;, &quot;yellow&quot;);</code></pre> <p>You can use whitespace and the <code>=&gt;</code> operator to lay them out more nicely:</p> <pre><code>my %fruit_color = ( apple =&gt; &quot;red&quot;, banana =&gt; &quot;yellow&quot;, );</code></pre> <p>To get at hash elements:</p> <pre><code>$fruit_color{&quot;apple&quot;}; # gives &quot;red&quot;</code></pre> <p>You can get at lists of keys and values with <code>keys()</code> and <code>values()</code>.</p> <pre><code>my @fruits = keys %fruit_colors; my @colors = values %fruit_colors;</code></pre> <p>Hashes have no particular internal order, though you can sort the keys and loop through them.</p> <p>Just like special scalars and arrays, there are also special hashes. The most well known of these is <code>%ENV</code> which contains environment variables. Read all about it (and other special variables) in <a href="/5.8.4/perlvar">perlvar</a>.</p> </dd> </dl> <p>Scalars, arrays and hashes are documented more fully in <a href="/5.8.4/perldata">perldata</a>.</p> <p>More complex data types can be constructed using references, which allow you to build lists and hashes within lists and hashes.</p> <p>A reference is a scalar value and can refer to any other Perl data type. So by storing a reference as the value of an array or hash element, you can easily create lists and hashes within lists and hashes. The following example shows a 2 level hash of hash structure using anonymous hash references.</p> <pre><code>my $variables = { scalar =&gt; { description =&gt; &quot;single item&quot;, sigil =&gt; &#39;$&#39;, }, array =&gt; { description =&gt; &quot;ordered list of items&quot;, sigil =&gt; &#39;@&#39;, }, hash =&gt; { description =&gt; &quot;key/value pairs&quot;, sigil =&gt; &#39;%&#39;, }, }; print &quot;Scalars begin with a $variables-&gt;{&#39;scalar&#39;}-&gt;{&#39;sigil&#39;}\n&quot;;</code></pre> <p>Exhaustive information on the topic of references can be found in <a href="/5.8.4/perlreftut">perlreftut</a>, <a href="/5.8.4/perllol">perllol</a>, <a href="/5.8.4/perlref">perlref</a> and <a href="/5.8.4/perldsc">perldsc</a>.</p> <h2 id="Variable-scoping"><a class="permalink" href="#Variable-scoping">#</a><a id="Variable"></a>Variable scoping</h2> <p>Throughout the previous section all the examples have used the syntax:</p> <pre><code>my $var = &quot;value&quot;;</code></pre> <p>The <code>my</code> is actually not required; you could just use:</p> <pre><code>$var = &quot;value&quot;;</code></pre> <p>However, the above usage will create global variables throughout your program, which is bad programming practice. <code>my</code> creates lexically scoped variables instead. The variables are scoped to the block (i.e. a bunch of statements surrounded by curly-braces) in which they are defined.</p> <pre><code>my $a = &quot;foo&quot;; if ($some_condition) { my $b = &quot;bar&quot;; print $a; # prints &quot;foo&quot; print $b; # prints &quot;bar&quot; } print $a; # prints &quot;foo&quot; print $b; # prints nothing; $b has fallen out of scope</code></pre> <p>Using <code>my</code> in combination with a <code>use strict;</code> at the top of your Perl scripts means that the interpreter will pick up certain common programming errors. For instance, in the example above, the final <code>print $b</code> would cause a compile-time error and prevent you from running the program. Using <code>strict</code> is highly recommended.</p> <h2 id="Conditional-and-looping-constructs"><a class="permalink" href="#Conditional-and-looping-constructs">#</a><a id="Conditional"></a>Conditional and looping constructs</h2> <p>Perl has most of the usual conditional and looping constructs except for case/switch (but if you really want it, there is a Switch module in Perl 5.8 and newer, and on CPAN. See the section on modules, below, for more information about modules and CPAN).</p> <p>The conditions can be any Perl expression. See the list of operators in the next section for information on comparison and boolean logic operators, which are commonly used in conditional statements.</p> <dl> <dt id="if"><a class="permalink" href="#if">#</a>if</dt> <dd> <pre><code>if ( condition ) { ... } elsif ( other condition ) { ... } else { ... }</code></pre> <p>There&#39;s also a negated version of it:</p> <pre><code>unless ( condition ) { ... }</code></pre> <p>This is provided as a more readable version of <code>if (!<i>condition</i>)</code>.</p> <p>Note that the braces are required in Perl, even if you&#39;ve only got one line in the block. However, there is a clever way of making your one-line conditional blocks more English like:</p> <pre><code># the traditional way if ($zippy) { print &quot;Yow!&quot;; } # the Perlish post-condition way print &quot;Yow!&quot; if $zippy; print &quot;We have no bananas&quot; unless $bananas;</code></pre> </dd> <dt id="while"><a class="permalink" href="#while">#</a>while</dt> <dd> <pre><code>while ( condition ) { ... }</code></pre> <p>There&#39;s also a negated version, for the same reason we have <code>unless</code>:</p> <pre><code>until ( condition ) { ... }</code></pre> <p>You can also use <code>while</code> in a post-condition:</p> <pre><code>print &quot;LA LA LA\n&quot; while 1; # loops forever</code></pre> </dd> <dt id="for"><a class="permalink" href="#for">#</a>for</dt> <dd> <p>Exactly like C:</p> <pre><code>for ($i=0; $i &lt;= $max; $i++) { ... }</code></pre> <p>The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning <code>foreach</code> loop.</p> </dd> <dt id="foreach"><a class="permalink" href="#foreach">#</a>foreach</dt> <dd> <pre><code>foreach (@array) { print &quot;This element is $_\n&quot;; } # you don&#39;t have to use the default $_ either... foreach my $key (keys %hash) { print &quot;The value of $key is $hash{$key}\n&quot;; }</code></pre> </dd> </dl> <p>For more detail on looping constructs (and some that weren&#39;t mentioned in this overview) see <a href="/5.8.4/perlsyn">perlsyn</a>.</p> <h2 id="Builtin-operators-and-functions"><a class="permalink" href="#Builtin-operators-and-functions">#</a><a id="Builtin"></a>Builtin operators and functions</h2> <p>Perl comes with a wide selection of builtin functions. Some of the ones we&#39;ve already seen include <code>print</code>, <code>sort</code> and <code>reverse</code>. A list of them is given at the start of <a href="/5.8.4/perlfunc">perlfunc</a> and you can easily read about any given function by using <code>perldoc -f <i>functionname</i></code>.</p> <p>Perl operators are documented in full in <a href="/5.8.4/perlop">perlop</a>, but here are a few of the most common ones:</p> <dl> <dt id="Arithmetic"><a class="permalink" href="#Arithmetic">#</a>Arithmetic</dt> <dd> <pre><code class="plaintext">+ addition - subtraction * multiplication / division</code></pre> </dd> <dt id="Numeric-comparison"><a class="permalink" href="#Numeric-comparison">#</a><a id="Numeric"></a>Numeric comparison</dt> <dd> <pre><code class="plaintext">== equality != inequality &lt; less than &gt; greater than &lt;= less than or equal &gt;= greater than or equal</code></pre> </dd> <dt id="String-comparison"><a class="permalink" href="#String-comparison">#</a><a id="String"></a>String comparison</dt> <dd> <pre><code class="plaintext">eq equality ne inequality lt less than gt greater than le less than or equal ge greater than or equal</code></pre> <p>(Why do we have separate numeric and string comparisons? Because we don&#39;t have special variable types, and Perl needs to know whether to sort numerically (where 99 is less than 100) or alphabetically (where 100 comes before 99).</p> </dd> <dt id="Boolean-logic"><a class="permalink" href="#Boolean-logic">#</a><a id="Boolean"></a>Boolean logic</dt> <dd> <pre><code class="plaintext">&amp;&amp; and || or ! not</code></pre> <p>(<code>and</code>, <code>or</code> and <code>not</code> aren&#39;t just in the above table as descriptions of the operators -- they&#39;re also supported as operators in their own right. They&#39;re more readable than the C-style operators, but have different precedence to <code>&amp;&amp;</code> and friends. Check <a href="/5.8.4/perlop">perlop</a> for more detail.)</p> </dd> <dt id="Miscellaneous"><a class="permalink" href="#Miscellaneous">#</a>Miscellaneous</dt> <dd> <pre><code class="plaintext">= assignment . string concatenation x string multiplication .. range operator (creates a list of numbers)</code></pre> </dd> </dl> <p>Many operators can be combined with a <code>=</code> as follows:</p> <pre><code>$a += 1; # same as $a = $a + 1 $a -= 1; # same as $a = $a - 1 $a .= &quot;\n&quot;; # same as $a = $a . &quot;\n&quot;;</code></pre> <h2 id="Files-and-I/O"><a class="permalink" href="#Files-and-I/O">#</a><a id="Files"></a><a id="Files-and-I-O"></a>Files and I/O</h2> <p>You can open a file for input or output using the <code>open()</code> function. It&#39;s documented in extravagant detail in <a href="/5.8.4/perlfunc">perlfunc</a> and <a href="/5.8.4/perlopentut">perlopentut</a>, but in short:</p> <pre><code>open(INFILE, &quot;input.txt&quot;) or die &quot;Can&#39;t open input.txt: $!&quot;; open(OUTFILE, &quot;&gt;output.txt&quot;) or die &quot;Can&#39;t open output.txt: $!&quot;; open(LOGFILE, &quot;&gt;&gt;my.log&quot;) or die &quot;Can&#39;t open logfile: $!&quot;;</code></pre> <p>You can read from an open filehandle using the <code>&lt;&gt;</code> operator. In scalar context it reads a single line from the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list:</p> <pre><code>my $line = &lt;INFILE&gt;; my @lines = &lt;INFILE&gt;;</code></pre> <p>Reading in the whole file at one time is called slurping. It can be useful but it may be a memory hog. Most text file processing can be done a line at a time with Perl&#39;s looping constructs.</p> <p>The <code>&lt;&gt;</code> operator is most often seen in a <code>while</code> loop:</p> <pre><code>while (&lt;INFILE&gt;) { # assigns each line in turn to $_ print &quot;Just read in this line: $_&quot;; }</code></pre> <p>We&#39;ve already seen how to print to standard output using <code>print()</code>. However, <code>print()</code> can also take an optional first argument specifying which filehandle to print to:</p> <pre><code>print STDERR &quot;This is your final warning.\n&quot;; print OUTFILE $record; print LOGFILE $logmessage;</code></pre> <p>When you&#39;re done with your filehandles, you should <code>close()</code> them (though to be honest, Perl will clean up after you if you forget):</p> <pre><code>close INFILE;</code></pre> <h2 id="Regular-expressions"><a class="permalink" href="#Regular-expressions">#</a><a id="Regular"></a>Regular expressions</h2> <p>Perl&#39;s regular expression support is both broad and deep, and is the subject of lengthy documentation in <a href="/5.8.4/perlrequick">perlrequick</a>, <a href="/5.8.4/perlretut">perlretut</a>, and elsewhere. However, in short:</p> <dl> <dt id="Simple-matching"><a class="permalink" href="#Simple-matching">#</a><a id="Simple"></a>Simple matching</dt> <dd> <pre><code>if (/foo/) { ... } # true if $_ contains &quot;foo&quot; if ($a =~ /foo/) { ... } # true if $a contains &quot;foo&quot;</code></pre> <p>The <code>//</code> matching operator is documented in <a href="/5.8.4/perlop">perlop</a>. It operates on <code>$_</code> by default, or can be bound to another variable using the <code>=~</code> binding operator (also documented in <a href="/5.8.4/perlop">perlop</a>).</p> </dd> <dt id="Simple-substitution"><a class="permalink" href="#Simple-substitution">#</a><a id="Simple1"></a>Simple substitution</dt> <dd> <pre><code>s/foo/bar/; # replaces foo with bar in $_ $a =~ s/foo/bar/; # replaces foo with bar in $a $a =~ s/foo/bar/g; # replaces ALL INSTANCES of foo with bar in $a</code></pre> <p>The <code>s///</code> substitution operator is documented in <a href="/5.8.4/perlop">perlop</a>.</p> </dd> <dt id="More-complex-regular-expressions"><a class="permalink" href="#More-complex-regular-expressions">#</a><a id="More"></a>More complex regular expressions</dt> <dd> <p>You don&#39;t just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. These are documented at great length in <a href="/5.8.4/perlre">perlre</a>, but for the meantime, here&#39;s a quick cheat sheet:</p> <pre><code class="plaintext">. a single character \s a whitespace character (space, tab, newline) \S non-whitespace character \d a digit (0-9) \D a non-digit \w a word character (a-z, A-Z, 0-9, _) \W a non-word character [aeiou] matches a single character in the given set [^aeiou] matches a single character outside the given set (foo|bar|baz) matches any of the alternatives specified ^ start of string $ end of string</code></pre> <p>Quantifiers can be used to specify how many of the previous thing you want to match on, where &quot;thing&quot; means either a literal character, one of the metacharacters listed above, or a group of characters or metacharacters in parentheses.</p> <pre><code class="plaintext">* zero or more of the previous thing + one or more of the previous thing ? zero or one of the previous thing {3} matches exactly 3 of the previous thing {3,6} matches between 3 and 6 of the previous thing {3,} matches 3 or more of the previous thing</code></pre> <p>Some brief examples:</p> <pre><code>/^\d+/ string starts with one or more digits /^$/ nothing in the string (start and end are adjacent) /(\d\s){3}/ a three digits, each followed by a whitespace character (eg &quot;3 4 5 &quot;) /(a.)+/ matches a string in which every odd-numbered letter is a (eg &quot;abacadaf&quot;) # This loop reads from STDIN, and prints non-blank lines: while (&lt;&gt;) { next if /^$/; print; }</code></pre> </dd> <dt id="Parentheses-for-capturing"><a class="permalink" href="#Parentheses-for-capturing">#</a><a id="Parentheses"></a>Parentheses for capturing</dt> <dd> <p>As well as grouping, parentheses serve a second purpose. They can be used to capture the results of parts of the regexp match for later use. The results end up in <code>$1</code>, <code>$2</code> and so on.</p> <pre><code># a cheap and nasty way to break an email address up into parts if ($email =~ /([^@])+@(.+)/) { print &quot;Username is $1\n&quot;; print &quot;Hostname is $2\n&quot;; }</code></pre> </dd> <dt id="Other-regexp-features"><a class="permalink" href="#Other-regexp-features">#</a><a id="Other"></a>Other regexp features</dt> <dd> <p>Perl regexps also support backreferences, lookaheads, and all kinds of other complex details. Read all about them in <a href="/5.8.4/perlrequick">perlrequick</a>, <a href="/5.8.4/perlretut">perlretut</a>, and <a href="/5.8.4/perlre">perlre</a>.</p> </dd> </dl> <h2 id="Writing-subroutines"><a class="permalink" href="#Writing-subroutines">#</a><a id="Writing"></a>Writing subroutines</h2> <p>Writing subroutines is easy:</p> <pre><code>sub log { my $logmessage = shift; print LOGFILE $logmessage; }</code></pre> <p>What&#39;s that <code>shift</code>? Well, the arguments to a subroutine are available to us as a special array called <code>@_</code> (see <a href="/5.8.4/perlvar">perlvar</a> for more on that). The default argument to the <code>shift</code> function just happens to be <code>@_</code>. So <code>my $logmessage = shift;</code> shifts the first item off the list of arguments and assigns it to <code>$logmessage</code>.</p> <p>We can manipulate <code>@_</code> in other ways too:</p> <pre><code>my ($logmessage, $priority) = @_; # common my $logmessage = $_[0]; # uncommon, and ugly</code></pre> <p>Subroutines can also return values:</p> <pre><code>sub square { my $num = shift; my $result = $num * $num; return $result; }</code></pre> <p>For more information on writing subroutines, see <a href="/5.8.4/perlsub">perlsub</a>.</p> <h2 id="OO-Perl"><a class="permalink" href="#OO-Perl">#</a><a id="OO"></a>OO Perl</h2> <p>OO Perl is relatively simple and is implemented using references which know what sort of object they are based on Perl&#39;s concept of packages. However, OO Perl is largely beyond the scope of this document. Read <a href="/5.8.4/perlboot">perlboot</a>, <a href="/5.8.4/perltoot">perltoot</a>, <a href="/5.8.4/perltooc">perltooc</a> and <a href="/5.8.4/perlobj">perlobj</a>.</p> <p>As a beginning Perl programmer, your most common use of OO Perl will be in using third-party modules, which are documented below.</p> <h2 id="Using-Perl-modules"><a class="permalink" href="#Using-Perl-modules">#</a><a id="Using"></a>Using Perl modules</h2> <p>Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( http://www.cpan.org/ ). A number of popular modules are included with the Perl distribution itself.</p> <p>Categories of modules range from text manipulation to network protocols to database integration to graphics. A categorized list of modules is also available from CPAN.</p> <p>To learn how to install modules you download from CPAN, read <a href="/5.8.4/perlmodinstall">perlmodinstall</a></p> <p>To learn how to use a particular module, use <code>perldoc <i>Module::Name</i></code>. Typically you will want to <code>use <i>Module::Name</i></code>, which will then give you access to exported functions or an OO interface to the module.</p> <p><a href="/5.8.4/perlfaq">perlfaq</a> contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.</p> <p><a href="/5.8.4/perlmod">perlmod</a> describes Perl modules in general. <a href="/5.8.4/perlmodlib">perlmodlib</a> lists the modules which came with your Perl installation.</p> <p>If you feel the urge to write Perl modules, <a href="/5.8.4/perlnewmod">perlnewmod</a> will give you good advice.</p> <h1 id="AUTHOR"><a class="permalink" href="#AUTHOR">#</a>AUTHOR</h1> <p>Kirrily &quot;Skud&quot; Robert &lt;skud@cpan.org&gt;</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