мета-данные страницы
  •  
Загрузка не удалась. Возможно, проблемы с правами доступа?

Это старая версия документа!


<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<!-- saved from url=(0017)http://localhost/ -->
<script language="JavaScript" src="../../displayToc.js"></script>
<script language="JavaScript" src="../../tocParas.js"></script>
<script language="JavaScript" src="../../tocTab.js"></script>
<link rel="stylesheet" type="text/css" href="../../scineplex.css">
<title>perlintro -- a brief introduction and overview of Perl</title>
<link rel="stylesheet" href="../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />
</head>

<body>

<!-- INDEX BEGIN -->
<div name="index">
<script>writelinks('__top__',2);</script>
<h1><a>perlintro -- a brief introduction and overview of Perl</a></h1>
<p><a name="__index__"></a></p>


<ul>

	<li><a href="#name">NAME</a></li>
	<li><a href="#description">DESCRIPTION</a></li>
	<ul>

		<li><a href="#what_is_perl">What is Perl?</a></li>
		<li><a href="#running_perl_programs">Running Perl programs</a></li>
		<li><a href="#safety_net">Safety net</a></li>
		<li><a href="#basic_syntax_overview">Basic syntax overview</a></li>
		<li><a href="#perl_variable_types">Perl variable types</a></li>
		<li><a href="#variable_scoping">Variable scoping</a></li>
		<li><a href="#conditional_and_looping_constructs">Conditional and looping constructs</a></li>
		<li><a href="#builtin_operators_and_functions">Builtin operators and functions</a></li>
		<li><a href="#files_and_i_o">Files and I/O</a></li>
		<li><a href="#regular_expressions">Regular expressions</a></li>
		<li><a href="#writing_subroutines">Writing subroutines</a></li>
		<li><a href="#oo_perl">OO Perl</a></li>
		<li><a href="#using_perl_modules">Using Perl modules</a></li>
	</ul>

	<li><a href="#author">AUTHOR</a></li>
</ul>

<hr name="index" />
</div>
<!-- INDEX END -->

<p>
</p>
<h1><a name="name">NAME</a></h1>
<p>perlintro -- a brief introduction and overview of Perl</p>
<p>
</p>
<hr />
<h1><a name="description">DESCRIPTION</a></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' Perl and understand roughly what it'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
<em>strongly</em> 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="../../lib/pods/perltoc.html">the perltoc manpage</a>.</p>
<p>Throughout this document you'll see references to other parts of the
Perl documentation.  You can read that documentation using the <code>perldoc

command or whatever method you're using to read this document.</p> <p> </p> <h2><a name=«what_is_perl»>What is Perl?</a></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'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's most impressive collections of third-party modules.</p> <p>Different definitions of Perl are given in <a href=«../../lib/pods/perl.html»>the perl manpage</a>, <a href=«../../lib/pods/perlfaq1.html»>the perlfaq1 manpage</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's at least worth writing about.</p> <p> </p> <h2><a name=«running_perl_programs»>Running Perl programs</a></h2> <p>To run a Perl program from the Unix command line:</p> <pre>

  perl progname.pl</pre>

<p>Alternatively, put this as the first line of your script:</p> <pre>

  <span class="comment">#!/usr/bin/env perl</span>

</pre> <p>… and run the script as

/path/to/script.pl

. Of course, it'll need to be executable first, so

chmod 755 script.pl

(under Unix).</p> <p>(This start line assumes you have the <strong>env</strong> program. You can also put directly the path to your perl executable, like in

#!/usr/bin/perl

).</p> <p>For more information, including instructions for other platforms such as Windows and Mac OS, read <a href=«../../lib/pods/perlrun.html»>the perlrun manpage</a>.</p> <p> </p> <h2><a name=«safety_net»>Safety net</a></h2> <p>Perl by default is very forgiving. In order to make it more robust it is recommended to start every program with the following lines:</p> <pre>

  <span class="comment">#!/usr/bin/perl</span>
  <span class="keyword">use</span> <span class="variable">strict</span><span class="operator">;</span>
  <span class="keyword">use</span> <span class="variable">warnings</span><span class="operator">;</span>

</pre> <p>The two additional lines request from perl to catch various common problems in your code. They check different things so you need both. A potential problem caught by

use strict;

will cause your code to stop immediately when it is encountered, while

use warnings;

will merely give a warning (like the command-line switch <strong>-w</strong>) and let your code run. To read more about them check their respective manual pages at <a href=«../../lib/strict.html»>the strict manpage</a> and <a href=«../../lib/warnings.html»>the warnings manpage</a>.</p> <p> </p> <h2><a name=«basic_syntax_overview»>Basic syntax overview</a></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

main()

function or anything of that kind.</p> <p>Perl statements end in a semi-colon:</p> <pre>

  <span class="keyword">print</span> <span class="string">"Hello, world"</span><span class="operator">;</span>

</pre> <p>Comments start with a hash symbol and run to the end of the line</p> <pre>

  <span class="comment"># This is a comment</span>

</pre> <p>Whitespace is irrelevant:</p> <pre>

  <span class="keyword">print</span>
      <span class="string">"Hello, world"</span>
      <span class="operator">;</span>

</pre> <p>… except inside quoted strings:</p> <pre>

  <span class="comment"># this would print with a linebreak in the middle</span>
  <span class="keyword">print</span> <span class="string">"Hello
  world"</span><span class="operator">;</span>

</pre> <p>Double quotes or single quotes may be used around literal strings:</p> <pre>

  <span class="keyword">print</span> <span class="string">"Hello, world"</span><span class="operator">;</span>
  <span class="keyword">print</span> <span class="string">'Hello, world'</span><span class="operator">;</span>

</pre> <p>However, only double quotes &quot;interpolate&quot; variables and special characters such as newlines (<a href=«../../lib/pods/perlrun.html#n»>

\n

</a>):</p> <pre>

  <span class="keyword">print</span> <span class="string">"Hello, </span><span class="variable">$name</span><span class="string">\n"</span><span class="operator">;</span>     <span class="comment"># works fine</span>
  <span class="keyword">print</span> <span class="string">'Hello, $name\n'</span><span class="operator">;</span>     <span class="comment"># prints $name\n literally</span>

</pre> <p>Numbers don't need quotes around them:</p> <pre>

  <span class="keyword">print</span> <span class="number">42</span><span class="operator">;</span>

</pre> <p>You can use parentheses for functions' arguments or omit them according to your personal taste. They are only required occasionally to clarify issues of precedence.</p> <pre>

  <span class="keyword">print</span><span class="operator">(</span><span class="string">"Hello, world\n"</span><span class="operator">);</span>
  <span class="keyword">print</span> <span class="string">"Hello, world\n"</span><span class="operator">;</span>

</pre> <p>More detailed information about Perl syntax can be found in <a href=«../../lib/pods/perlsyn.html»>the perlsyn manpage</a>.</p> <p> </p> <h2><a name=«perl_variable_types»>Perl variable types</a></h2> <p>Perl has three main variable types: scalars, arrays, and hashes.</p> <dl> <dt><strong><a name=«scalars» class=«item»>Scalars</a></strong>

<dd> <p>A scalar represents a single value:</p> </dd> <dd> <pre>

  <span class="keyword">my</span> <span class="variable">$animal</span> <span class="operator">=</span> <span class="string">"camel"</span><span class="operator">;</span>
  <span class="keyword">my</span> <span class="variable">$answer</span> <span class="operator">=</span> <span class="number">42</span><span class="operator">;</span>

</pre> </dd> <dd> <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, but you have to declare them using the <a href=«../../lib/pods/perlfunc.html#my»>

my

</a> keyword the first time you use them. (This is one of the requirements of

use strict;

.)</p> </dd> <dd> <p>Scalar values can be used in various ways:</p> </dd> <dd> <pre>

  <span class="keyword">print</span> <span class="variable">$animal</span><span class="operator">;</span>
  <span class="keyword">print</span> <span class="string">"The animal is </span><span class="variable">$animal</span><span class="string">\n"</span><span class="operator">;</span>
  <span class="keyword">print</span> <span class="string">"The square of </span><span class="variable">$answer</span><span class="string"> is "</span><span class="operator">,</span> <span class="variable">$answer</span> <span class="operator">*</span> <span class="variable">$answer</span><span class="operator">,</span> <span class="string">"\n"</span><span class="operator">;</span>

</pre> </dd> <dd> <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=«../../lib/pods/perlvar.html»>the perlvar manpage</a>. The only one you need to know about for now is <a href=«../../lib/pods/perlvar.html#»><code>$_</code></a> which is the &quot;default variable&quot;. It's used as the default argument to a number of functions in Perl, and it's set implicitly by certain looping constructs.</p> </dd> <dd> <pre> print; # prints contents of $_ by default </pre> </dd> </li> <dt><strong><a name=«arrays» class=«item»>Arrays</a></strong> <dd> <p>An array represents a list of values:</p> </dd> <dd> <pre> my @animals = («camel», «llama», «owl»); my @numbers = (23, 42, 69); my @mixed = («camel», 42, 1.23); </pre> </dd> <dd> <p>Arrays are zero-indexed. Here's how you get at elements in an array:</p> </dd> <dd> <pre> print $animals[0]; # prints «camel» print $animals[1]; # prints «llama» </pre> </dd> <dd> <p>The special variable <code>$#array</code> tells you the index of the last element of an array:</p> </dd> <dd> <pre> print $mixed[$#mixed]; # last element, prints 1.23 </pre> </dd> <dd> <p>You might be tempted to use <code>$#array + 1</code> to tell you how many items there are in an array. Don'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> </dd> <dd> <pre> if (@animals &lt; 5) { } </pre> </dd> <dd> <p>The elements we're getting from the array start with a <code>$</code> because we're getting just a single value out of the array – you ask for a scalar, you get a scalar.</p> </dd> <dd> <p>To get multiple values from an array:</p> </dd> <dd> <pre> @animals[0,1]; # gives («camel», «llama»); @animals[0..2]; # gives («camel», «llama», «owl»); @animals[1..$#animals]; # gives all except the first element </pre> </dd> <dd> <p>This is called an &quot;array slice&quot;.</p> </dd> <dd> <p>You can do various useful things to lists:</p> </dd> <dd> <pre> my @sorted = sort @animals; my @backwards = reverse @numbers; </pre> </dd> <dd> <p>There are a couple of special arrays too, such as <a href=«../../lib/pods/perlvar.html#_argv»><code>@ARGV</code></a> (the command line arguments to your script) and <a href=«../../lib/pods/perlvar.html#»>

@_

</a> (the arguments passed to a subroutine). These are documented in <a href=«../../lib/pods/perlvar.html»>the perlvar manpage</a>.</p> </dd> </li> <dt><strong><a name=«hashes» class=«item»>Hashes</a></strong>

<dd> <p>A hash represents a set of key/value pairs:</p> </dd> <dd> <pre>

  <span class="keyword">my</span> <span class="variable">%fruit_color</span> <span class="operator">=</span> <span class="operator">(</span><span class="string">"apple"</span><span class="operator">,</span> <span class="string">"red"</span><span class="operator">,</span> <span class="string">"banana"</span><span class="operator">,</span> <span class="string">"yellow"</span><span class="operator">);</span>

</pre> </dd> <dd> <p>You can use whitespace and the

=&gt;

operator to lay them out more nicely:</p> </dd> <dd> <pre>

  <span class="keyword">my</span> <span class="variable">%fruit_color</span> <span class="operator">=</span> <span class="operator">(</span>
      <span class="string">apple</span>  <span class="operator">=&gt;</span> <span class="string">"red"</span><span class="operator">,</span>
      <span class="string">banana</span> <span class="operator">=&gt;</span> <span class="string">"yellow"</span><span class="operator">,</span>
  <span class="operator">);</span>

</pre> </dd> <dd> <p>To get at hash elements:</p> </dd> <dd> <pre>

  <span class="variable">$fruit_color</span><span class="operator">{</span><span class="string">"apple"</span><span class="operator">}</span><span class="operator">;</span>           <span class="comment"># gives "red"</span>

</pre> </dd> <dd> <p>You can get at lists of keys and values with <a href=«../../lib/pods/perlfunc.html#keys»>

keys()

</a> and <a href=«../../lib/pods/perlfunc.html#values»>

values()

</a>.</p> </dd> <dd> <pre>

  <span class="keyword">my</span> <span class="variable">@fruits</span> <span class="operator">=</span> <span class="keyword">keys</span> <span class="variable">%fruit_colors</span><span class="operator">;</span>
  <span class="keyword">my</span> <span class="variable">@colors</span> <span class="operator">=</span> <span class="keyword">values</span> <span class="variable">%fruit_colors</span><span class="operator">;</span>

</pre> </dd> <dd> <p>Hashes have no particular internal order, though you can sort the keys and loop through them.</p> </dd> <dd> <p>Just like special scalars and arrays, there are also special hashes. The most well known of these is <a href=«../../lib/pods/perlvar.html#_env»>

%ENV

</a> which contains environment variables. Read all about it (and other special variables) in <a href=«../../lib/pods/perlvar.html»>the perlvar manpage</a>.</p> </dd> </li> </dl> <p>Scalars, arrays and hashes are documented more fully in <a href=«../../lib/pods/perldata.html»>the perldata manpage</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>

  <span class="keyword">my</span> <span class="variable">$variables</span> <span class="operator">=</span> <span class="operator">{</span>
      <span class="string">scalar</span>  <span class="operator">=&gt;</span>  <span class="operator">{</span>
                   <span class="string">description</span> <span class="operator">=&gt;</span> <span class="string">"single item"</span><span class="operator">,</span>
                   <span class="string">sigil</span> <span class="operator">=&gt;</span> <span class="string">'$'</span><span class="operator">,</span>
                  <span class="operator">}</span><span class="operator">,</span>
      <span class="string">array</span>   <span class="operator">=&gt;</span>  <span class="operator">{</span>
                   <span class="string">description</span> <span class="operator">=&gt;</span> <span class="string">"ordered list of items"</span><span class="operator">,</span>
                   <span class="string">sigil</span> <span class="operator">=&gt;</span> <span class="string">'@'</span><span class="operator">,</span>
                  <span class="operator">}</span><span class="operator">,</span>
      <span class="string">hash</span>    <span class="operator">=&gt;</span>  <span class="operator">{</span>
                   <span class="string">description</span> <span class="operator">=&gt;</span> <span class="string">"key/value pairs"</span><span class="operator">,</span>
                   <span class="string">sigil</span> <span class="operator">=&gt;</span> <span class="string">'%'</span><span class="operator">,</span>
                  <span class="operator">}</span><span class="operator">,</span>
  <span class="operator">}</span><span class="operator">;</span>

</pre> <pre>

  <span class="keyword">print</span> <span class="string">"Scalars begin with a </span><span class="variable">$variables</span><span class="string">-&gt;{'scalar'}-&gt;{'sigil'}\n"</span><span class="operator">;</span>

</pre> <p>Exhaustive information on the topic of references can be found in <a href=«../../lib/pods/perlreftut.html»>the perlreftut manpage</a>, <a href=«../../lib/pods/perllol.html»>the perllol manpage</a>, <a href=«../../lib/pods/perlref.html»>the perlref manpage</a> and <a href=«../../lib/pods/perldsc.html»>the perldsc manpage</a>.</p> <p> </p> <h2><a name=«variable_scoping»>Variable scoping</a></h2> <p>Throughout the previous section all the examples have used the syntax:</p> <pre>

  <span class="keyword">my</span> <span class="variable">$var</span> <span class="operator">=</span> <span class="string">"value"</span><span class="operator">;</span>

</pre> <p>The <a href=«../../lib/pods/perlfunc.html#my»>

my

</a> is actually not required; you could just use:</p> <pre>

  <span class="variable">$var</span> <span class="operator">=</span> <span class="string">"value"</span><span class="operator">;</span>

</pre> <p>However, the above usage will create global variables throughout your program, which is bad programming practice. <a href=«../../lib/pods/perlfunc.html#my»>

my

</a> 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>

  <span class="keyword">my</span> <span class="variable">$x</span> <span class="operator">=</span> <span class="string">"foo"</span><span class="operator">;</span>
  <span class="keyword">my</span> <span class="variable">$some_condition</span> <span class="operator">=</span> <span class="number">1</span><span class="operator">;</span>
  <span class="keyword">if</span> <span class="operator">(</span><span class="variable">$some_condition</span><span class="operator">)</span> <span class="operator">{</span>
      <span class="keyword">my</span> <span class="variable">$y</span> <span class="operator">=</span> <span class="string">"bar"</span><span class="operator">;</span>
      <span class="keyword">print</span> <span class="variable">$x</span><span class="operator">;</span>           <span class="comment"># prints "foo"</span>
      <span class="keyword">print</span> <span class="variable">$y</span><span class="operator">;</span>           <span class="comment"># prints "bar"</span>
  <span class="operator">}</span>
  <span class="keyword">print</span> <span class="variable">$x</span><span class="operator">;</span>               <span class="comment"># prints "foo"</span>
  <span class="keyword">print</span> <span class="variable">$y</span><span class="operator">;</span>               <span class="comment"># prints nothing; $y has fallen out of scope</span>

</pre> <p>Using <a href=«../../lib/pods/perlfunc.html#my»>

my

</a> in combination with a

use strict;

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

print $b

would cause a compile-time error and prevent you from running the program. Using

strict

is highly recommended.</p> <p> </p> <h2><a name=«conditional_and_looping_constructs»>Conditional and looping constructs</a></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><strong><a name=«if» class=«item»>if</a></strong>

<dd> <pre>

  <span class="keyword">if</span> <span class="operator">(</span> <span class="variable">condition</span> <span class="operator">)</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span> <span class="keyword">elsif</span> <span class="operator">(</span> <span class="variable">other</span> <span class="variable">condition</span> <span class="operator">)</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span> <span class="keyword">else</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <p>There's also a negated version of it:</p> </dd> <dd> <pre>

  <span class="keyword">unless</span> <span class="operator">(</span> <span class="variable">condition</span> <span class="operator">)</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <p>This is provided as a more readable version of <a href=«#if»>

if (!condition)

</a>.</p> </dd> <dd> <p>Note that the braces are required in Perl, even if you'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> </dd> <dd> <pre>

  <span class="comment"># the traditional way</span>
  <span class="keyword">if</span> <span class="operator">(</span><span class="variable">$zippy</span><span class="operator">)</span> <span class="operator">{</span>
      <span class="keyword">print</span> <span class="string">"Yow!"</span><span class="operator">;</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <pre>

  <span class="comment"># the Perlish post-condition way</span>
  <span class="keyword">print</span> <span class="string">"Yow!"</span> <span class="keyword">if</span> <span class="variable">$zippy</span><span class="operator">;</span>
  <span class="keyword">print</span> <span class="string">"We have no bananas"</span> <span class="keyword">unless</span> <span class="variable">$bananas</span><span class="operator">;</span>

</pre> </dd> <dt><strong><a name=«while» class=«item»>while</a></strong>

<dd> <pre>

  <span class="keyword">while</span> <span class="operator">(</span> <span class="variable">condition</span> <span class="operator">)</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <p>There's also a negated version, for the same reason we have

unless

:</p> </dd> <dd> <pre>

  <span class="keyword">until</span> <span class="operator">(</span> <span class="variable">condition</span> <span class="operator">)</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <p>You can also use <a href=«#while»>

while

</a> in a post-condition:</p> </dd> <dd> <pre>

  <span class="keyword">print</span> <span class="string">"LA LA LA\n"</span> <span class="keyword">while</span> <span class="number">1</span><span class="operator">;</span>          <span class="comment"># loops forever</span>

</pre> </dd> <dt><strong><a name=«for» class=«item»>for</a></strong>

<dd> <p>Exactly like C:</p> </dd> <dd> <pre>

  <span class="keyword">for</span> <span class="operator">(</span><span class="variable">$i</span> <span class="operator">=</span> <span class="number">0</span><span class="operator">;</span> <span class="variable">$i</span> <span class="operator">&lt;=</span> <span class="variable">$max</span><span class="operator">;</span> <span class="variable">$i</span><span class="operator">++)</span> <span class="operator">{</span>
      <span class="operator">...</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <p>The C style for loop is rarely needed in Perl since Perl provides the more friendly list scanning <a href=«#foreach»>

foreach

</a> loop.</p> </dd> </li> <dt><strong><a name=«foreach» class=«item»>foreach</a></strong>

<dd> <pre>

  <span class="keyword">foreach</span> <span class="operator">(</span><span class="variable">@array</span><span class="operator">)</span> <span class="operator">{</span>
      <span class="keyword">print</span> <span class="string">"This element is </span><span class="variable">$_</span><span class="string">\n"</span><span class="operator">;</span>
  <span class="operator">}</span>

</pre> </dd> <dd> <pre>

  <span class="keyword">print</span> <span class="variable">$list</span><span class="operator">[</span><span class="variable">$_</span><span class="operator">]</span> <span class="keyword">foreach</span> <span class="number">0</span> <span class="operator">..</span> <span class="variable">$max</span><span class="operator">;</span>

</pre> </dd> <dd> <pre>

  <span class="comment"># you don't have to use the default $_ either...</span>
  <span class="keyword">foreach</span> <span class="keyword">my</span> <span class="variable">$key</span> <span class="operator">(</span><span class="keyword">keys</span> <span class="variable">%hash</span><span class="operator">)</span> <span class="operator">{</span>
      <span class="keyword">print</span> <span class="string">"The value of </span><span class="variable">$key</span><span class="string"> is </span><span class="variable">$hash</span><span class="string">{</span><span class="variable">$key</span><span class="string">}\n"</span><span class="operator">;</span>
  <span class="operator">}</span>

</pre> </dd> </dl> <p>For more detail on looping constructs (and some that weren't mentioned in this overview) see <a href=«../../lib/pods/perlsyn.html»>the perlsyn manpage</a>.</p> <p> </p> <h2><a name=«builtin_operators_and_functions»>Builtin operators and functions</a></h2> <p>Perl comes with a wide selection of builtin functions. Some of the ones we've already seen include <a href=«../../lib/pods/perlfunc.html#print»>

print

</a>, <a href=«../../lib/pods/perlfunc.html#sort»>

sort

</a> and <a href=«../../lib/pods/perlfunc.html#reverse»>

reverse

</a>. A list of them is given at the start of <a href=«../../lib/pods/perlfunc.html»>the perlfunc manpage</a> and you can easily read about any given function by using

perldoc -f functionname

.</p> <p>Perl operators are documented in full in <a href=«../../lib/pods/perlop.html»>the perlop manpage</a>, but here are a few of the most common ones:</p> <dl> <dt><strong><a name=«arithmetic» class=«item»>Arithmetic</a></strong>

<dd> <pre>

  +   addition
  -   subtraction
  *   multiplication
  /   division</pre>

</dd> <dt><strong><a name=«numeric_comparison» class=«item»>Numeric comparison</a></strong>

<dd> <pre>

  ==  equality
  !=  inequality
  &lt;   less than
  &gt;   greater than
  &lt;=  less than or equal
  &gt;=  greater than or equal</pre>

</dd> <dt><strong><a name=«string_comparison» class=«item»>String comparison</a></strong>

<dd> <pre>

  eq  equality
  ne  inequality
  lt  less than
  gt  greater than
  le  less than or equal
  ge  greater than or equal</pre>

</dd> <dd> <p>(Why do we have separate numeric and string comparisons? Because we don'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><strong><a name=«boolean_logic» class=«item»>Boolean logic</a></strong>

<dd> <pre>

  &amp;&amp;  and
  ||  or
  !   not</pre>

</dd> <dd> <p>(

and

,

or

and

not

aren't just in the above table as descriptions of the operators – they're also supported as operators in their own right. They're more readable than the C-style operators, but have different precedence to

&amp;&amp;

and friends. Check <a href=«../../lib/pods/perlop.html»>the perlop manpage</a> for more detail.)</p> </dd> <dt><strong><a name=«miscellaneous2» class=«item»>Miscellaneous</a></strong>

<dd> <pre>

  =   assignment
  .   string concatenation
  x   string multiplication
  ..  range operator (creates a list of numbers)</pre>

</dd> </dl> <p>Many operators can be combined with a

=

as follows:</p> <pre>

  <span class="variable">$a</span> <span class="operator">+=</span> <span class="number">1</span><span class="operator">;</span>        <span class="comment"># same as $a = $a + 1</span>
  <span class="variable">$a</span> <span class="operator">-=</span> <span class="number">1</span><span class="operator">;</span>        <span class="comment"># same as $a = $a - 1</span>
  <span class="variable">$a</span> <span class="operator">.=</span> <span class="string">"\n"</span><span class="operator">;</span>     <span class="comment"># same as $a = $a . "\n";</span>

</pre> <p> </p> <h2><a name=«files_and_i_o»>Files and I/O</a></h2> <p>You can open a file for input or output using the <a href=«../../lib/pods/perlfunc.html#open»>

open()

</a> function. It's documented in extravagant detail in <a href=«../../lib/pods/perlfunc.html»>the perlfunc manpage</a> and <a href=«../../lib/pods/perlopentut.html»>the perlopentut manpage</a>, but in short:</p> <pre>

  <span class="keyword">open</span><span class="operator">(</span><span class="keyword">my</span> <span class="variable">$in</span><span class="operator">,</span>  <span class="string">"&lt;"</span><span class="operator">,</span>  <span class="string">"input.txt"</span><span class="operator">)</span>  <span class="keyword">or</span> <span class="keyword">die</span> <span class="string">"Can't open input.txt: $!"</span><span class="operator">;</span>
  <span class="keyword">open</span><span class="operator">(</span><span class="keyword">my</span> <span class="variable">$out</span><span class="operator">,</span> <span class="string">"&gt;"</span><span class="operator">,</span>  <span class="string">"output.txt"</span><span class="operator">)</span> <span class="keyword">or</span> <span class="keyword">die</span> <span class="string">"Can't open output.txt: $!"</span><span class="operator">;</span>
  <span class="keyword">open</span><span class="operator">(</span><span class="keyword">my</span> <span class="variable">$log</span><span class="operator">,</span> <span class="string">"&gt;&gt;"</span><span class="operator">,</span> <span class="string">"my.log"</span><span class="operator">)</span>     <span class="keyword">or</span> <span class="keyword">die</span> <span class="string">"Can't open my.log: $!"</span><span class="operator">;</span>

</pre> <p>You can read from an open filehandle using the

&lt;&gt;

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>

  <span class="keyword">my</span> <span class="variable">$line</span>  <span class="operator">=</span> <span class="operator">&lt;</span><span class="variable">$in</span><span class="operator">&gt;;</span>
  <span class="keyword">my</span> <span class="variable">@lines</span> <span class="operator">=</span> <span class="operator">&lt;</span><span class="variable">$in</span><span class="operator">&gt;;</span>

</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's looping constructs.</p> <p>The

&lt;&gt;

operator is most often seen in a <a href=«#while»>

while

</a> loop:</p> <pre>

  <span class="keyword">while</span> <span class="operator">(&lt;</span><span class="variable">$in</span><span class="operator">&gt;)</span> <span class="operator">{</span>     <span class="comment"># assigns each line in turn to $_</span>
      <span class="keyword">print</span> <span class="string">"Just read in this line: </span><span class="variable">$_</span><span class="string">"</span><span class="operator">;</span>
  <span class="operator">}</span>

</pre> <p>We've already seen how to print to standard output using <a href=«../../lib/pods/perlfunc.html#print»>

print()

</a>. However, <a href=«../../lib/pods/perlfunc.html#print»>

print()

</a> can also take an optional first argument specifying which filehandle to print to:</p> <pre>

  <span class="keyword">print</span> <span class="variable">STDERR</span> <span class="string">"This is your final warning.\n"</span><span class="operator">;</span>
  <span class="keyword">print</span> <span class="variable">$out</span> <span class="variable">$record</span><span class="operator">;</span>
  <span class="keyword">print</span> <span class="variable">$log</span> <span class="variable">$logmessage</span><span class="operator">;</span>

</pre> <p>When you're done with your filehandles, you should <a href=«../../lib/pods/perlfunc.html#close»>

close()

</a> them (though to be honest, Perl will clean up after you if you forget):</p> <pre>

  <span class="keyword">close</span> <span class="variable">$in</span> <span class="keyword">or</span> <span class="keyword">die</span> <span class="string">"</span><span class="variable">$in</span><span class="string">: $!"</span><span class="operator">;</span>

</pre> <p> </p> <h2><a name=«regular_expressions»>Regular expressions</a></h2> <p>Perl's regular expression support is both broad and deep, and is the subject of lengthy documentation in <a href=«../../lib/pods/perlrequick.html»>the perlrequick manpage</a>, <a href=«../../lib/pods/perlretut.html»>the perlretut manpage</a>, and elsewhere. However, in short:</p> <dl> <dt><strong><a name=«simple_matching» class=«item»>Simple matching</a></strong>

<dd> <pre>

  <span class="keyword">if</span> <span class="operator">(</span><span class="regex">/foo/</span><span class="operator">)</span>       <span class="operator">{</span> <span class="operator">...</span> <span class="operator">}</span>  <span class="comment"># true if $_ contains "foo"</span>
  <span class="keyword">if</span> <span class="operator">(</span><span class="variable">$a</span> <span class="operator">=~</span> <span class="regex">/foo/</span><span class="operator">)</span> <span class="operator">{</span> <span class="operator">...</span> <span class="operator">}</span>  <span class="comment"># true if $a contains "foo"</span>

</pre> </dd> <dd> <p>The

//

matching operator is documented in <a href=«../../lib/pods/perlop.html»>the perlop manpage</a>. It operates on <a href=«../../lib/pods/perlvar.html#»><code>$_</code></a> by default, or can be bound to another variable using the <code>=~</code> binding operator (also documented in <a href=«../../lib/pods/perlop.html»>the perlop manpage</a>).</p> </dd> <dt><strong><a name=«simple_substitution» class=«item»>Simple substitution</a></strong> <dd> <pre> 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 </pre> </dd> <dd> <p>The <a href=«../../lib/pods/perlfunc.html#s_»><code>s/</code></a> substitution operator is documented in <a href=«../../lib/pods/perlop.html»>the perlop manpage</a>.</p> </dd> <dt><strong><a name=«more_complex_regular_expressions» class=«item»>More complex regular expressions</a></strong> <dd> <p>You don'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=«../../lib/pods/perlre.html»>the perlre manpage</a>, but for the meantime, here's a quick cheat sheet:</p> </dd> <dd> <pre> . 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</pre> </dd> <dd> <pre> ^ start of string $ end of string</pre> </dd> <dd> <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> </dd> <dd> <pre> * 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 </pre> </dd> <dd> <p>Some brief examples:</p> </dd> <dd> <pre> /^\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 «3 4 5 ») /(a.)+/ matches a string in which every odd-numbered letter is a (eg «abacadaf») </pre> </dd> <dd> <pre> # This loop reads from STDIN, and prints non-blank lines: while (&lt;&gt;) { next if /^$/; print; } </pre> </dd> </li> <dt><strong><a name=«parentheses_for_capturing» class=«item»>Parentheses for capturing</a></strong> <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> </dd> <dd> <pre> # a cheap and nasty way to break an email address up into parts </pre> </dd> <dd> <pre> if ($email =~ /([^@]+)@(.+)/) { print «Username is $1\n»; print «Hostname is $2\n»; } </pre> </dd> </li> <dt><strong><a name=«other_regexp_features» class=«item»>Other regexp features</a></strong> <dd> <p>Perl regexps also support backreferences, lookaheads, and all kinds of other complex details. Read all about them in <a href=«../../lib/pods/perlrequick.html»>the perlrequick manpage</a>, <a href=«../../lib/pods/perlretut.html»>the perlretut manpage</a>, and <a href=«../../lib/pods/perlre.html»>the perlre manpage</a>.</p> </dd> </li> </dl> <p> </p> <h2><a name=«writing_subroutines»>Writing subroutines</a></h2> <p>Writing subroutines is easy:</p> <pre> sub logger { my $logmessage = shift; open my $logfile, «&gt;&gt;», «my.log» or die «Could not open my.log: $!»; print $logfile $logmessage; } </pre> <p>Now we can use the subroutine just as any other built-in function:</p> <pre> logger(«We have a logger subroutine!»); </pre> <p>What's that <a href=«../../lib/pods/perlfunc.html#shift»><code>shift</code></a>? Well, the arguments to a subroutine are available to us as a special array called <a href=«../../lib/pods/perlvar.html#»><code>@_</code></a> (see <a href=«../../lib/pods/perlvar.html»>the perlvar manpage</a> for more on that). The default argument to the <a href=«../../lib/pods/perlfunc.html#shift»><code>shift</code></a> function just happens to be <a href=«../../lib/pods/perlvar.html#»><code>@_</code></a>. 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 <a href=«../../lib/pods/perlvar.html#__»><code>@_</code></a> in other ways too:</p> <pre> my ($logmessage, $priority) = @_; # common my $logmessage = $_[0]; # uncommon, and ugly </pre> <p>Subroutines can also return values:</p> <pre> sub square { my $num = shift; my $result = $num * $num; return $result; } </pre> <p>Then use it like:</p> <pre> $sq = square(8); </pre> <p>For more information on writing subroutines, see <a href=«../../lib/pods/perlsub.html»>the perlsub manpage</a>.</p> <p> </p> <h2><a name=«oo_perl»>OO Perl</a></h2> <p>OO Perl is relatively simple and is implemented using references which know what sort of object they are based on Perl's concept of packages. However, OO Perl is largely beyond the scope of this document. Read <a href=«../../lib/pods/perlboot.html»>the perlboot manpage</a>, <a href=«../../lib/pods/perltoot.html»>the perltoot manpage</a>, <a href=«../../lib/pods/perltooc.html»>the perltooc manpage</a> and <a href=«../../lib/pods/perlobj.html»>the perlobj manpage</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> <p> </p> <h2><a name=«using_perl_modules»>Using Perl modules</a></h2> <p>Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN ( <a href=«http://www.cpan.org/»>http://www.cpan.org/</a> ). 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=«../../lib/pods/perlmodinstall.html»>the perlmodinstall manpage</a></p> <p>To learn how to use a particular module, use <code>perldoc Module::Name</code>. Typically you will want to <code>use Module::Name</code>, which will then give you access to exported functions or an OO interface to the module.</p> <p><a href=«../../lib/pods/perlfaq.html»>the perlfaq manpage</a> contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use.</p> <p><a href=«../../lib/pods/perlmod.html»>the perlmod manpage</a> describes Perl modules in general. <a href=«../../lib/pods/perlmodlib.html»>the perlmodlib manpage</a> lists the modules which came with your Perl installation.</p> <p>If you feel the urge to write Perl modules, <a href=«../../lib/pods/perlnewmod.html»>the perlnewmod manpage</a> will give you good advice.</p> <p> </p> <hr /> <h1><a name=«author»>AUTHOR</a></h1> <p>Kirrily &quot;Skud&quot; Robert &lt;<a href=«mailto:skud@cpan.org»>skud@cpan.org</a>&gt;</p> </body> </html> </code>