Perl language structure
- 28 min read
- 6 chapters
Related on Lably
Through Input/output, String (computer science) and Comment (computer programming)
Basic syntax
In Perl, the minimal Hello World program may be written as follows:
<span id="mwGg"></span><span class="k" id="mwGw">print</span><span class="w" id="mwHA"> </span><span class="s" id="mwHQ">"Hello, World!\n"</span>
This prints the string Hello, World! and a newline, symbolically expressed by an n character whose interpretation is altered by the preceding escape character (a backslash). Since version 5.10, the new 'say' builtin produces the same effect even more simply:
<span id="mwLA"></span><span class="n" id="mwLQ">say</span><span class="w" id="mwLg"> </span><span class="s" id="mwLw">"Hello, World!"</span>
An entire Perl program may also be specified as a command-line parameter to Perl, so the same program can also be executed from the command line (example shown for Unix):
<span id="mwMw"></span><span class="nv" id="mwNA">$</span><span class="w" id="mwNQ"> </span><span class="nv" id="mwNg">perl</span><span class="w" id="mwNw"> </span><span class="o" id="mwOA">-</span><span class="n" id="mwOQ">e</span><span class="w" id="mwOg"> </span><span class="s" id="mwOw">'print "Hello, World!\n"'</span>
The canonical form of the program is slightly more verbose:
<span id="mwPw"></span><span class="ch" id="mwQA">#!/usr/bin/env perl</span> <span class="k" id="mwQQ">print</span><span class="w" id="mwQg"> </span><span class="s" id="mwQw">"Hello, World!\n"</span><span class="p" id="mwRA">;</span>
The hash mark character introduces a comment in Perl, which runs up to the end of the line of code and is ignored by the compiler (except on Windows). The comment used here is of a special kind: it's called the shebang line. This tells Unix-like operating systems to find the Perl interpreter, making it possible to invoke the program without explicitly mentioning perl. (Note that, on Microsoft Windows systems, Perl programs are typically invoked by associating the .pl extension with the Perl interpreter. In order to deal with such circumstances, perl detects the shebang line and parses it for switches.)
The second line in the canonical form includes a semicolon, which is used to separate statements in Perl. With only a single statement in a block or file, a separator is unnecessary, so it can be omitted from the minimal form of the program—or more generally from the final statement in any block or file. The canonical form includes it, because it is common to terminate every statement even when it is unnecessary to do so, as this makes editing easier: code can be added to, or moved away from, the end of a block or file without having to adjust semicolons.
Version 5.10 of Perl introduces a say function that implicitly appends a newline character to its output, making the minimal "Hello World" program even shorter:
<span id="mwVw"></span><span class="k" id="mwWA">use</span><span class="w" id="mwWQ"> </span><span class="mf" id="mwWg">5.010</span><span class="p" id="mwWw">;</span><span class="w" id="mwXA"> </span><span class="c1" id="mwXQ"># must be present to import the new 5.10 functions, notice that it is 5.010 not 5.10</span> <span class="n" id="mwXg">say</span><span class="w" id="mwXw"> </span><span class="s" id="mwYA">'Hello, World!'</span>
Sign in to keep reading
5 more chapters are free with a Lably account.
Data types
Perl has a number of fundamental data types. The most commonly used and discussed are scalars, arrays, hashes, filehandles, and subroutines:
Scalar values
String values (literals) must be enclosed by quotes. Enclosing a string in double quotes allows the values of variables whose names appear in the string to automatically replace the variable name (or be interpolated) in the string. Enclosing a string in single quotes prevents variable interpolation.
For example, if $name is "Jim":
- then
print("My name is $name")will print"My name is Jim"(interpolation within double quotes), - but
print('My name is $name')will print"My name is $name"(no interpolation within single quotes).
To include a double quotation mark in a string, precede it with a backslash or enclose the string in single quotes. To include a single quotation mark, precede it with a backslash or enclose the string in double quotes.
Strings can also be quoted with the q and qq quote-like operators:
'this'andq(this)are identical,"$this"andqq($this)are identical.
Finally, multiline strings can be defined using here documents:
<span id="mwyQ"></span><span class="nv" id="mwyg">$multilined_string</span><span class="w" id="mwyw"> </span><span class="o" id="mwzA">=</span><span class="w" id="mwzQ"> </span><span class="s" id="mwzg"><<</span><span class="dl" id="mwzw">EOF</span><span class="s" id="mw0A">;</span> <span class="s" id="mw0Q">This is my multilined string</span> <span class="s" id="mw0g">note that I am terminating it with the word "EOF".</span> <span class="dl" id="mw0w">EOF</span>
Numbers (numeric constants) do not require quotation. Perl will convert numbers into strings and vice versa depending on the context in which they are used. When strings are converted into numbers, trailing non-numeric parts of the strings are discarded. If no leading part of a string is numeric, the string will be converted to the number 0. In the following example, the strings $n and $m are treated as numbers. This code prints the number '5'. The values of the variables remain the same. Note that in Perl, + is always the numeric addition operator. The string concatenation operator is the period.
<span id="mw2g"></span><span class="nv" id="mw2w">$n</span><span class="w" id="mw3A"> </span><span class="o" id="mw3Q">=</span><span class="w" id="mw3g"> </span><span class="s" id="mw3w">'3 apples'</span><span class="p" id="mw4A">;</span> <span class="nv" id="mw4Q">$m</span><span class="w" id="mw4g"> </span><span class="o" id="mw4w">=</span><span class="w" id="mw5A"> </span><span class="s" id="mw5Q">'2 oranges'</span><span class="p" id="mw5g">;</span> <span class="k" id="mw5w">print</span><span class="w" id="mw6A"> </span><span class="nv" id="mw6Q">$n</span><span class="w" id="mw6g"> </span><span class="o" id="mw6w">+</span><span class="w" id="mw7A"> </span><span class="nv" id="mw7Q">$m</span><span class="p" id="mw7g">;</span>
Functions are provided for the rounding of fractional values to integer values: int chops off the fractional part, rounding towards zero; POSIX::ceil and POSIX::floor round always up and always down, respectively. The number-to-string conversion of printf "%f" or sprintf "%f" round out even, use bankers' rounding.
Perl also has a boolean context that it uses in evaluating conditional statements. The following values all evaluate as false in Perl:
<span id="mw-w"></span><span class="nv" id="mw_A">$false</span><span class="w" id="mw_Q"> </span><span class="o" id="mw_g">=</span><span class="w" id="mw_w"> </span><span class="mi" id="mwAQA">0</span><span class="p" id="mwAQE">;</span><span class="w" id="mwAQI"> </span><span class="c1" id="mwAQM"># the number zero</span> <span class="nv" id="mwAQQ">$false</span><span class="w" id="mwAQU"> </span><span class="o" id="mwAQY">=</span><span class="w" id="mwAQc"> </span><span class="mf" id="mwAQg">0.0</span><span class="p" id="mwAQk">;</span><span class="w" id="mwAQo"> </span><span class="c1" id="mwAQs"># the number zero as a float</span> <span class="nv" id="mwAQw">$false</span><span class="w" id="mwAQ0"> </span><span class="o" id="mwAQ4">=</span><span class="w" id="mwAQ8"> </span><span class="mb" id="mwARA">0b0</span><span class="p" id="mwARE">;</span><span class="w" id="mwARI"> </span><span class="c1" id="mwARM"># the number zero in binary</span> <span class="nv" id="mwARQ">$false</span><span class="w" id="mwARU"> </span><span class="o" id="mwARY">=</span><span class="w" id="mwARc"> </span><span class="mh" id="mwARg">0x0</span><span class="p" id="mwARk">;</span><span class="w" id="mwARo"> </span><span class="c1" id="mwARs"># the number zero in hexadecimal</span> <span class="nv" id="mwARw">$false</span><span class="w" id="mwAR0"> </span><span class="o" id="mwAR4">=</span><span class="w" id="mwAR8"> </span><span class="s" id="mwASA">'0'</span><span class="p" id="mwASE">;</span><span class="w" id="mwASI"> </span><span class="c1" id="mwASM"># the string zero</span> <span class="nv" id="mwASQ">$false</span><span class="w" id="mwASU"> </span><span class="o" id="mwASY">=</span><span class="w" id="mwASc"> </span><span class="s" id="mwASg">""</span><span class="p" id="mwASk">;</span><span class="w" id="mwASo"> </span><span class="c1" id="mwASs"># the empty string</span> <span class="nv" id="mwASw">$false</span><span class="w" id="mwAS0"> </span><span class="o" id="mwAS4">=</span><span class="w" id="mwAS8"> </span><span class="p" id="mwATA">();</span><span class="w" id="mwATE"> </span><span class="c1" id="mwATI"># the empty list</span> <span class="nv" id="mwATM">$false</span><span class="w" id="mwATQ"> </span><span class="o" id="mwATU">=</span><span class="w" id="mwATY"> </span><span class="nb" id="mwATc">undef</span><span class="p" id="mwATg">;</span><span class="w" id="mwATk"> </span><span class="c1" id="mwATo"># the return value from undef</span> <span class="nv" id="mwATs">$false</span><span class="w" id="mwATw"> </span><span class="o" id="mwAT0">=</span><span class="w" id="mwAT4"> </span><span class="mi" id="mwAT8">2</span><span class="o" id="mwAUA">-</span><span class="mi" id="mwAUE">3</span><span class="o" id="mwAUI">+</span><span class="mi" id="mwAUM">1</span><span class="w" id="mwAUQ"> </span><span class="c1" id="mwAUU"># computes to 0 that is converted to "0" so it is false</span>
All other (non-zero evaluating) values evaluate to true. This includes the odd self-describing literal string of "0 but true", which in fact is 0 as a number, but true when used as a boolean. All non-numeric strings also have this property, but this particular string is truncated by Perl without a numeric warning. A less explicit but more conceptually portable version of this string is '0E0' or '0e0', which does not rely on characters being evaluated as 0, because '0E0' is literally zero times ten to the power zero. The empty hash {} is also true; in this context {} is not an empty block, because perl -e 'print ref {}' returns HASH.
Evaluated boolean expressions are also scalar values. The documentation does not promise which particular value of true or false is returned. Many boolean operators return 1 for true and the empty-string for false. The defined() function determines whether a variable has any value set. In the above examples, defined($false) is true for every value except undef.
If either 1 or 0 are specifically needed, an explicit conversion can be done using the conditional operator:
<span id="mwAVg"></span><span class="k" id="mwAVk">my</span><span class="w" id="mwAVo"> </span><span class="nv" id="mwAVs">$real_result</span><span class="w" id="mwAVw"> </span><span class="o" id="mwAV0">=</span><span class="w" id="mwAV4"> </span><span class="nv" id="mwAV8">$boolean_result</span><span class="w" id="mwAWA"> </span><span class="p" id="mwAWE">?</span><span class="w" id="mwAWI"> </span><span class="mi" id="mwAWM">1</span><span class="w" id="mwAWQ"> </span><span class="p" id="mwAWU">:</span><span class="w" id="mwAWY"> </span><span class="mi" id="mwAWc">0</span><span class="p" id="mwAWg">;</span>
Array values
An array value (or list) is specified by listing its elements, separated by commas, enclosed by parentheses (at least where required by operator precedence).
<span id="mwAW4"></span><span class="nv" id="mwAW8">@scores</span><span class="w" id="mwAXA"> </span><span class="o" id="mwAXE">=</span><span class="w" id="mwAXI"> </span><span class="p" id="mwAXM">(</span><span class="mi" id="mwAXQ">32</span><span class="p" id="mwAXU">,</span><span class="w" id="mwAXY"> </span><span class="mi" id="mwAXc">45</span><span class="p" id="mwAXg">,</span><span class="w" id="mwAXk"> </span><span class="mi" id="mwAXo">16</span><span class="p" id="mwAXs">,</span><span class="w" id="mwAXw"> </span><span class="mi" id="mwAX0">5</span><span class="p" id="mwAX4">);</span>
The qw() quote-like operator allows the definition of a list of strings without typing of quotes and commas. Almost any delimiter can be used instead of parentheses. The following lines are equivalent:
<span id="mwAYI"></span><span class="nv" id="mwAYM">@names</span><span class="w" id="mwAYQ"> </span><span class="o" id="mwAYU">=</span><span class="w" id="mwAYY"> </span><span class="p" id="mwAYc">(</span><span class="s" id="mwAYg">'Billy'</span><span class="p" id="mwAYk">,</span><span class="w" id="mwAYo"> </span><span class="s" id="mwAYs">'Joe'</span><span class="p" id="mwAYw">,</span><span class="w" id="mwAY0"> </span><span class="s" id="mwAY4">'Jim-Bob'</span><span class="p" id="mwAY8">);</span> <span class="nv" id="mwAZA">@names</span><span class="w" id="mwAZE"> </span><span class="o" id="mwAZI">=</span><span class="w" id="mwAZM"> </span><span class="sx" id="mwAZQ">qw(Billy Joe Jim-Bob)</span><span class="p" id="mwAZU">;</span>
The split function returns a list of strings, which are split from a string expression using a delimiter string or regular expression.
<span id="mwAZk"></span><span class="nv" id="mwAZo">@scores</span><span class="w" id="mwAZs"> </span><span class="o" id="mwAZw">=</span><span class="w" id="mwAZ0"> </span><span class="nb" id="mwAZ4">split</span><span class="p" id="mwAZ8">(</span><span class="s" id="mwAaA">','</span><span class="p" id="mwAaE">,</span><span class="w" id="mwAaI"> </span><span class="s" id="mwAaM">'32,45,16,5'</span><span class="p" id="mwAaQ">);</span>
Individual elements of a list are accessed by providing a numerical index in square brackets. The scalar sigil must be used. Sublists (array slices) can also be specified, using a range or list of numeric indices in brackets. The array sigil is used in this case. For example, $month[3] is "April" (the first element in an array has an index value of 0), and @month[4..6] is ("May", "June", "July").
Hash values
Perl programmers may initialize a hash (or associative array) from a list of key/value pairs. If the keys are separated from the values with the => operator (sometimes called a fat comma), rather than a comma, they may be unquoted (barewords). The following lines are equivalent:
<span id="mwAbY"></span><span class="nv" id="mwAbc">%favorite</span><span class="w" id="mwAbg"> </span><span class="o" id="mwAbk">=</span><span class="w" id="mwAbo"> </span><span class="p" id="mwAbs">(</span><span class="s" id="mwAbw">'joe'</span><span class="p" id="mwAb0">,</span><span class="w" id="mwAb4"> </span><span class="s" id="mwAb8">"red"</span><span class="p" id="mwAcA">,</span><span class="w" id="mwAcE"> </span><span class="s" id="mwAcI">'sam'</span><span class="p" id="mwAcM">,</span><span class="w" id="mwAcQ"> </span><span class="s" id="mwAcU">"blue"</span><span class="p" id="mwAcY">);</span> <span class="nv" id="mwAcc">%favorite</span><span class="w" id="mwAcg"> </span><span class="o" id="mwAck">=</span><span class="w" id="mwAco"> </span><span class="p" id="mwAcs">(</span><span class="n" id="mwAcw">joe</span><span class="w" id="mwAc0"> </span><span class="o" id="mwAc4">=></span><span class="w" id="mwAc8"> </span><span class="s" id="mwAdA">'red'</span><span class="p" id="mwAdE">,</span><span class="w" id="mwAdI"> </span><span class="n" id="mwAdM">sam</span><span class="w" id="mwAdQ"> </span><span class="o" id="mwAdU">=></span><span class="w" id="mwAdY"> </span><span class="s" id="mwAdc">'blue'</span><span class="p" id="mwAdg">);</span>
Individual values in a hash are accessed by providing the corresponding key, in curly braces. The $ sigil identifies the accessed element as a scalar. For example, $favorite{joe} equals 'red'. A hash can also be initialized by setting its values individually:
<span id="mwAd8"></span><span class="nv" id="mwAeA">$favorite</span><span class="p" id="mwAeE">{</span><span class="n" id="mwAeI">joe</span><span class="p" id="mwAeM">}</span><span class="w" id="mwAeQ"> </span><span class="o" id="mwAeU">=</span><span class="w" id="mwAeY"> </span><span class="s" id="mwAec">'red'</span><span class="p" id="mwAeg">;</span> <span class="nv" id="mwAek">$favorite</span><span class="p" id="mwAeo">{</span><span class="n" id="mwAes">sam</span><span class="p" id="mwAew">}</span><span class="w" id="mwAe0"> </span><span class="o" id="mwAe4">=</span><span class="w" id="mwAe8"> </span><span class="s" id="mwAfA">'blue'</span><span class="p" id="mwAfE">;</span> <span class="nv" id="mwAfI">$favorite</span><span class="p" id="mwAfM">{</span><span class="n" id="mwAfQ">oscar</span><span class="p" id="mwAfU">}</span><span class="w" id="mwAfY"> </span><span class="o" id="mwAfc">=</span><span class="w" id="mwAfg"> </span><span class="s" id="mwAfk">'green'</span><span class="p" id="mwAfo">;</span>Multiple elements may be accessed using the @ sigil instead (identifying the result as a list). For example, @favorite{'joe', 'sam'} equals ('red', 'blue').
Filehandles
Filehandles provide read and write access to resources. These are most often files on disk, but can also be a device, a pipe, or even a scalar value.
Originally, filehandles could only be created with package variables, using the ALL_CAPS convention to distinguish it from other variables. Perl 5.6 and newer also accept a scalar variable, which will be set (autovivified) to a reference to an anonymous filehandle, in place of a named filehandle.
Typeglob values
A typeglob value is a symbol table entry. The main use of typeglobs is creating symbol table aliases. For example:
<span id="mwAgg"></span><span class="o" id="mwAgk">*</span><span class="n" id="mwAgo">PI</span><span class="w" id="mwAgs"> </span><span class="o" id="mwAgw">=</span><span class="w" id="mwAg0"> </span><span class="o" id="mwAg4">\</span><span class="mf" id="mwAg8">3.141592653</span><span class="p" id="mwAhA">;</span><span class="w" id="mwAhE"> </span><span class="c1" id="mwAhI"># creating constant scalar $PI</span> <span class="o" id="mwAhM">*</span><span class="n" id="mwAhQ">this</span><span class="w" id="mwAhU"> </span><span class="o" id="mwAhY">=</span><span class="w" id="mwAhc"> </span><span class="o" id="mwAhg">*</span><span class="n" id="mwAhk">that</span><span class="p" id="mwAho">;</span><span class="w" id="mwAhs"> </span><span class="c1" id="mwAhw"># creating aliases for all data types 'this' to all data types 'that'</span>
Array functions
The number of elements in an array can be determined either by evaluating the array in scalar context or with the help of the $# sigil. The latter gives the index of the last element in the array, not the number of elements. The expressions scalar(@array) and ($#array + 1) are equivalent.
Hash functions
There are a few functions that operate on entire hashes. The keys function takes a hash and returns the list of its keys. Similarly, the values function returns a hash's values. Note that the keys and values are returned in a consistent but arbitrary order.
<span id="mwAio"></span><span class="c1" id="mwAis"># Every call to each returns the next key/value pair.</span> <span class="c1" id="mwAiw"># All values will be eventually returned, but their order</span> <span class="c1" id="mwAi0"># cannot be predicted.</span> <span class="k" id="mwAi4">while</span><span class="w" id="mwAi8"> </span><span class="p" id="mwAjA">((</span><span class="nv" id="mwAjE">$name</span><span class="p" id="mwAjI">,</span><span class="w" id="mwAjM"> </span><span class="nv" id="mwAjQ">$address</span><span class="p" id="mwAjU">)</span><span class="w" id="mwAjY"> </span><span class="o" id="mwAjc">=</span><span class="w" id="mwAjg"> </span><span class="nb" id="mwAjk">each</span><span class="w" id="mwAjo"> </span><span class="nv" id="mwAjs">%addressbook</span><span class="p" id="mwAjw">)</span><span class="w" id="mwAj0"> </span><span class="p" id="mwAj4">{</span> <span class="w" id="mwAj8"> </span><span class="k" id="mwAkA">print</span><span class="w" id="mwAkE"> </span><span class="s" id="mwAkI">"$name lives at $address\n"</span><span class="p" id="mwAkM">;</span> <span class="p" id="mwAkQ">}</span> <span class="c1" id="mwAkU"># Similar to the above, but sorted alphabetically</span> <span class="k" id="mwAkY">foreach</span><span class="w" id="mwAkc"> </span><span class="k" id="mwAkg">my</span><span class="w" id="mwAkk"> </span><span class="nv" id="mwAko">$next_name</span><span class="w" id="mwAks"> </span><span class="p" id="mwAkw">(</span><span class="nb" id="mwAk0">sort</span><span class="w" id="mwAk4"> </span><span class="nb" id="mwAk8">keys</span><span class="w" id="mwAlA"> </span><span class="nv" id="mwAlE">%addressbook</span><span class="p" id="mwAlI">)</span><span class="w" id="mwAlM"> </span><span class="p" id="mwAlQ">{</span> <span class="w" id="mwAlU"> </span><span class="k" id="mwAlY">print</span><span class="w" id="mwAlc"> </span><span class="s" id="mwAlg">"$next_name lives at $addressbook{$next_name}\n"</span><span class="p" id="mwAlk">;</span> <span class="p" id="mwAlo">}</span>Control structures
Perl has several kinds of control structures.
It has block-oriented control structures, similar to those in the C, JavaScript, and Java programming languages. Conditions are surrounded by parentheses, and controlled blocks are surrounded by braces:
<i id="mwAmM">label</i> while ( <i id="mwAmQ">cond</i> ) { ... } <i id="mwAmU">label</i> while ( <i id="mwAmY">cond</i> ) { ... } continue { ... } <i id="mwAmc">label</i> for ( <i id="mwAmg">init-expr</i> ; <i id="mwAmk">cond-expr</i> ; <i id="mwAmo">incr-expr</i> ) { ... } <i id="mwAms">label</i> foreach <i id="mwAmw">var</i> ( <i id="mwAm0">list</i> ) { ... } <i id="mwAm4">label</i> foreach <i id="mwAm8">var</i> ( <i id="mwAnA">list</i> ) { ... } continue { ... } if ( <i id="mwAnE">cond</i> ) { ... } if ( <i id="mwAnI">cond</i> ) { ... } else { ... } if ( <i id="mwAnM">cond</i> ) { ... } elsif ( <i id="mwAnQ">cond</i> ) { ... } else { ... }Where only a single statement is being controlled, statement modifiers provide a more-concise syntax:
<i id="mwAnc">statement</i> if <i id="mwAng">cond</i> ; <i id="mwAnk">statement</i> unless <i id="mwAno">cond</i> ; <i id="mwAns">statement</i> while <i id="mwAnw">cond</i> ; <i id="mwAn0">statement</i> until <i id="mwAn4">cond</i> ; <i id="mwAn8">statement</i> foreach <i id="mwAoA">list</i> ;
Short-circuit logical operators are commonly used to affect control flow at the expression level:
<i id="mwAoU">expr</i> and <i id="mwAoY">expr</i> <i id="mwAoc">expr</i> && <i id="mwAog">expr</i> <i id="mwAok">expr</i> or <i id="mwAoo">expr</i> <i id="mwAos">expr</i> <span typeof="mw:Nowiki" id="mwAow">||</span> <i id="mwAo0">expr</i>
(The "and" and "or" operators are similar to && and || but have lower precedence, which makes it easier to use them to control entire statements.)
The flow control keywords next (corresponding to C's continue), last (corresponding to C's break), return, and redo are expressions, so they can be used with short-circuit operators.
Perl also has two implicit looping constructs, each of which has two forms:
<i id="mwApo">results</i> = grep { ... } <i id="mwAps">list</i> <i id="mwApw">results</i> = grep <i id="mwAp0">expr</i>, <i id="mwAp4">list</i> <i id="mwAp8">results</i> = map { ... } <i id="mwAqA">list</i> <i id="mwAqE">results</i> = map <i id="mwAqI">expr</i>, <i id="mwAqM">list</i>grep returns all elements of list for which the controlled block or expression evaluates to true. map evaluates the controlled block or expression for each element of list and returns a list of the resulting values. These constructs enable a simple functional programming style.
Up until the 5.10.0 release, there was no switch statement in Perl 5. From 5.10.0 onward, a multi-way branch statement called given/when is available, which takes the following form:
<code class="tpl-codett mw-highlight mw-highlight-lang-perl mw-content-ltr" style="border:none; padding: 0px 0px; color:var(--color-base, #202122); background:transparent;" dir="ltr" typeof="mw:Extension/syntaxhighlight mw:Transclusion" about="#mwt82" data-mw='{"name":"syntaxhighlight","attrs":{"lang":"perl","class":"tpl-codett","style":"border:none; padding: 0px 0px; color:var(--color-base, #202122); background:transparent;","inline":"1"},"body":{"extsrc":"use v5.10; # must be present to import the new 5.10 functions"},"parts":[{"template":{"target":{"wt":"codett","href":"./Template:Codett"},"params":{"2":{"wt":"perl"},"1":{"wt":"use v5.10; # must be present to import the new 5.10 functions"}},"i":0}}]}' id="mwAq8"><span class="k" id="mwArA">use</span><span class="w" id="mwArE"> </span><span class="nn" id="mwArI">v5</span><span class="mf" id="mwArM">.10</span><span class="p" id="mwArQ">;</span><span class="w" id="mwArU"> </span><span class="c1" id="mwArY"># must be present to import the new 5.10 functions</span></code> given ( <i id="mwArc">expr</i> ) { when ( <i id="mwArg">cond</i> ) { ... } default { ... } }Syntactically, this structure behaves similarly to switch statements found in other languages, but with a few important differences. The largest is that unlike switch/case structures, given/when statements break execution after the first successful branch, rather than waiting for explicitly defined break commands. Conversely, explicit continues are instead necessary to emulate switch behavior.
For those not using Perl 5.10, the Perl documentation describes a half-dozen ways to achieve the same effect by using other control structures. There is also a Switch module, which provides functionality modeled on that of sister language Raku. It is implemented using a source filter, so its use is unofficially discouraged.
Perl includes a goto label statement, but it is rarely used. Situations where a goto is called for in other languages don't occur as often in Perl, because of its breadth of flow control options.
There is also a goto &sub statement that performs a tail call. It terminates the current subroutine and immediately calls the specified sub. This is used in situations where a caller can perform more-efficient stack management than Perl itself (typically because no change to the current stack is required), and in deep recursion, tail calling can have substantial positive impact on performance, because it avoids the overhead of scope/stack management on return.
Subroutines
Subroutines are defined with the sub keyword and are invoked simply by naming them. If the subroutine in question has not yet been declared, invocation requires either parentheses after the function name or an ampersand (&) before it. But using & without parentheses will also implicitly pass the arguments of the current subroutine to the one called, and using & with parentheses will bypass prototypes.
<span id="mwAtY"></span><span class="c1" id="mwAtc"># Calling a subroutine</span> <span class="c1" id="mwAtg"># Parentheses are required here if the subroutine is defined later in the code</span> <span class="n" id="mwAtk">foo</span><span class="p" id="mwAto">();</span> <span class="o" id="mwAts">&</span><span class="n" id="mwAtw">foo</span><span class="p" id="mwAt0">;</span><span class="w" id="mwAt4"> </span><span class="c1" id="mwAt8"># (this also works, but has other consequences regarding arguments passed to the subroutine)</span> <span class="c1" id="mwAuA"># Defining a subroutine</span> <span class="k" id="mwAuE">sub</span><span class="w" id="mwAuI"> </span><span class="nf" id="mwAuM">foo</span><span class="w" id="mwAuQ"> </span><span class="p" id="mwAuU">{</span><span class="w" id="mwAuY"> </span><span class="err" id="mwAuc">…</span><span class="w" id="mwAug"> </span><span class="p" id="mwAuk">}</span> <span class="n" id="mwAuo">foo</span><span class="p" id="mwAus">;</span><span class="w" id="mwAuw"> </span><span class="c1" id="mwAu0"># Here parentheses are not required</span>A list of arguments may be provided after the subroutine name. Arguments may be scalars, lists, or hashes.
<span id="mwAvE"></span><span class="n" id="mwAvI">foo</span><span class="w" id="mwAvM"> </span><span class="nv" id="mwAvQ">$x</span><span class="p" id="mwAvU">,</span><span class="w" id="mwAvY"> </span><span class="nv" id="mwAvc">@y</span><span class="p" id="mwAvg">,</span><span class="w" id="mwAvk"> </span><span class="nv" id="mwAvo">%z</span><span class="p" id="mwAvs">;</span>
The parameters to a subroutine do not need to be declared as to either number or type; in fact, they may vary from call to call. Any validation of parameters must be performed explicitly inside the subroutine.
Arrays are expanded to their elements; hashes are expanded to a list of key/value pairs; and the whole lot is passed into the subroutine as one flat list of scalars.
Whatever arguments are passed are available to the subroutine in the special array @_. The elements of @_ are references to the actual arguments; changing an element of @_ changes the corresponding argument.
Elements of @_ may be accessed by subscripting it in the usual way.
<span id="mwAwY"></span><span class="nv" id="mwAwc">$_</span><span class="p" id="mwAwg">[</span><span class="mi" id="mwAwk">0</span><span class="p" id="mwAwo">],</span><span class="w" id="mwAws"> </span><span class="nv" id="mwAww">$_</span><span class="p" id="mwAw0">[</span><span class="mi" id="mwAw4">1</span><span class="p" id="mwAw8">]</span>
However, the resulting code can be difficult to read, and the parameters have pass-by-reference semantics, which may be undesirable.
One common idiom is to assign @_ to a list of named variables.
<span id="mwAxY"></span><span class="k" id="mwAxc">my</span><span class="w" id="mwAxg"> </span><span class="p" id="mwAxk">(</span><span class="nv" id="mwAxo">$x</span><span class="p" id="mwAxs">,</span><span class="w" id="mwAxw"> </span><span class="nv" id="mwAx0">$y</span><span class="p" id="mwAx4">,</span><span class="w" id="mwAx8"> </span><span class="nv" id="mwAyA">$z</span><span class="p" id="mwAyE">)</span><span class="w" id="mwAyI"> </span><span class="o" id="mwAyM">=</span><span class="w" id="mwAyQ"> </span><span class="nv" id="mwAyU">@_</span><span class="p" id="mwAyY">;</span>
This provides mnemonic parameter names and implements pass-by-value semantics. The my keyword indicates that the following variables are lexically scoped to the containing block.
Another idiom is to shift parameters off of @_. This is especially common when the subroutine takes only one argument or for handling the $self argument in object-oriented modules.
<span id="mwAy8"></span><span class="k" id="mwAzA">my</span><span class="w" id="mwAzE"> </span><span class="nv" id="mwAzI">$x</span><span class="w" id="mwAzM"> </span><span class="o" id="mwAzQ">=</span><span class="w" id="mwAzU"> </span><span class="nb" id="mwAzY">shift</span><span class="p" id="mwAzc">;</span>
Subroutines may assign @_ to a hash to simulate named arguments; this is recommended in Perl Best Practices for subroutines that are likely to ever have more than three parameters.
<span id="mwA0I"></span><span class="k" id="mwA0M">sub</span><span class="w" id="mwA0Q"> </span><span class="nf" id="mwA0U">function1</span><span class="w" id="mwA0Y"> </span><span class="p" id="mwA0c">{</span> <span class="w" id="mwA0g"> </span><span class="k" id="mwA0k">my</span><span class="w" id="mwA0o"> </span><span class="nv" id="mwA0s">%args</span><span class="w" id="mwA0w"> </span><span class="o" id="mwA00">=</span><span class="w" id="mwA04"> </span><span class="nv" id="mwA08">@_</span><span class="p" id="mwA1A">;</span> <span class="w" id="mwA1E"> </span><span class="k" id="mwA1I">print</span><span class="w" id="mwA1M"> </span><span class="s" id="mwA1Q">"'x' argument was '$args{x}'\n"</span><span class="p" id="mwA1U">;</span> <span class="p" id="mwA1Y">}</span> <span class="n" id="mwA1c">function1</span><span class="p" id="mwA1g">(</span><span class="w" id="mwA1k"> </span><span class="n" id="mwA1o">x</span><span class="w" id="mwA1s"> </span><span class="o" id="mwA1w">=></span><span class="w" id="mwA10"> </span><span class="mi" id="mwA14">23</span><span class="w" id="mwA18"> </span><span class="p" id="mwA2A">);</span>Subroutines may return values.
<span id="mwA2Q"></span><span class="k" id="mwA2U">return</span><span class="w" id="mwA2Y"> </span><span class="mi" id="mwA2c">42</span><span class="p" id="mwA2g">,</span><span class="w" id="mwA2k"> </span><span class="nv" id="mwA2o">$x</span><span class="p" id="mwA2s">,</span><span class="w" id="mwA2w"> </span><span class="nv" id="mwA20">@y</span><span class="p" id="mwA24">,</span><span class="w" id="mwA28"> </span><span class="nv" id="mwA3A">%z</span><span class="p" id="mwA3E">;</span>
If the subroutine does not exit via a return statement, it returns the last expression evaluated within the subroutine body. Arrays and hashes in the return value are expanded to lists of scalars, just as they are for arguments.
The returned expression is evaluated in the calling context of the subroutine; this can surprise the unwary.
<span id="mwA3c"></span><span class="k" id="mwA3g">sub</span><span class="w" id="mwA3k"> </span><span class="nf" id="mwA3o">list</span><span class="w" id="mwA3s"> </span><span class="p" id="mwA3w">{</span><span class="w" id="mwA30"> </span><span class="p" id="mwA34">(</span><span class="mi" id="mwA38">4</span><span class="p" id="mwA4A">,</span><span class="w" id="mwA4E"> </span><span class="mi" id="mwA4I">5</span><span class="p" id="mwA4M">,</span><span class="w" id="mwA4Q"> </span><span class="mi" id="mwA4U">6</span><span class="p" id="mwA4Y">)</span><span class="w" id="mwA4c"> </span><span class="p" id="mwA4g">}</span> <span class="k" id="mwA4k">sub</span><span class="w" id="mwA4o"> </span><span class="nf" id="mwA4s">array</span><span class="w" id="mwA4w"> </span><span class="p" id="mwA40">{</span><span class="w" id="mwA44"> </span><span class="nv" id="mwA48">@x</span><span class="w" id="mwA5A"> </span><span class="o" id="mwA5E">=</span><span class="w" id="mwA5I"> </span><span class="p" id="mwA5M">(</span><span class="mi" id="mwA5Q">4</span><span class="p" id="mwA5U">,</span><span class="w" id="mwA5Y"> </span><span class="mi" id="mwA5c">5</span><span class="p" id="mwA5g">,</span><span class="w" id="mwA5k"> </span><span class="mi" id="mwA5o">6</span><span class="p" id="mwA5s">);</span><span class="w" id="mwA5w"> </span><span class="nv" id="mwA50">@x</span><span class="w" id="mwA54"> </span><span class="p" id="mwA58">}</span> <span class="nv" id="mwA6A">$x</span><span class="w" id="mwA6E"> </span><span class="o" id="mwA6I">=</span><span class="w" id="mwA6M"> </span><span class="n" id="mwA6Q">list</span><span class="p" id="mwA6U">;</span><span class="w" id="mwA6Y"> </span><span class="c1" id="mwA6c"># returns 6 - last element of list</span> <span class="nv" id="mwA6g">$x</span><span class="w" id="mwA6k"> </span><span class="o" id="mwA6o">=</span><span class="w" id="mwA6s"> </span><span class="n" id="mwA6w">array</span><span class="p" id="mwA60">;</span><span class="w" id="mwA64"> </span><span class="c1" id="mwA68"># returns 3 - number of elements in list</span> <span class="nv" id="mwA7A">@x</span><span class="w" id="mwA7E"> </span><span class="o" id="mwA7I">=</span><span class="w" id="mwA7M"> </span><span class="n" id="mwA7Q">list</span><span class="p" id="mwA7U">;</span><span class="w" id="mwA7Y"> </span><span class="c1" id="mwA7c"># returns (4, 5, 6)</span> <span class="nv" id="mwA7g">@x</span><span class="w" id="mwA7k"> </span><span class="o" id="mwA7o">=</span><span class="w" id="mwA7s"> </span><span class="n" id="mwA7w">array</span><span class="p" id="mwA70">;</span><span class="w" id="mwA74"> </span><span class="c1" id="mwA78"># returns (4, 5, 6)</span>A subroutine can discover its calling context with the wantarray function.
<span id="mwA8Q"></span><span class="k" id="mwA8U">sub</span><span class="w" id="mwA8Y"> </span><span class="nf" id="mwA8c">either</span><span class="w" id="mwA8g"> </span><span class="p" id="mwA8k">{</span> <span class="w" id="mwA8o"> </span><span class="k" id="mwA8s">return</span><span class="w" id="mwA8w"> </span><span class="nb" id="mwA80">wantarray</span><span class="w" id="mwA84"> </span><span class="p" id="mwA88">?</span><span class="w" id="mwA9A"> </span><span class="p" id="mwA9E">(</span><span class="mi" id="mwA9I">1</span><span class="p" id="mwA9M">,</span><span class="w" id="mwA9Q"> </span><span class="mi" id="mwA9U">2</span><span class="p" id="mwA9Y">)</span><span class="w" id="mwA9c"> </span><span class="p" id="mwA9g">:</span><span class="w" id="mwA9k"> </span><span class="s" id="mwA9o">'Oranges'</span><span class="p" id="mwA9s">;</span> <span class="p" id="mwA9w">}</span> <span class="nv" id="mwA90">$x</span><span class="w" id="mwA94"> </span><span class="o" id="mwA98">=</span><span class="w" id="mwA-A"> </span><span class="n" id="mwA-E">either</span><span class="p" id="mwA-I">;</span><span class="w" id="mwA-M"> </span><span class="c1" id="mwA-Q"># returns "Oranges"</span> <span class="nv" id="mwA-U">@x</span><span class="w" id="mwA-Y"> </span><span class="o" id="mwA-c">=</span><span class="w" id="mwA-g"> </span><span class="n" id="mwA-k">either</span><span class="p" id="mwA-o">;</span><span class="w" id="mwA-s"> </span><span class="c1" id="mwA-w"># returns (1, 2)</span>Anonymous functions
Perl 5 supports anonymous functions, as follows:
<span id="mwA_U"></span><span class="p" id="mwA_Y">(</span><span class="k" id="mwA_c">sub</span><span class="w" id="mwA_g"> </span><span class="p" id="mwA_k">{</span><span class="w" id="mwA_o"> </span><span class="k" id="mwA_s">print</span><span class="w" id="mwA_w"> </span><span class="s" id="mwA_0">"I got called\n"</span><span class="w" id="mwA_4"> </span><span class="p" id="mwA_8">})</span><span class="o" id="mwBAA">-></span><span class="p" id="mwBAE">();</span><span class="w" id="mwBAI"> </span><span class="c1" id="mwBAM"># 1. fully anonymous, called as created</span> <span class="k" id="mwBAQ">my</span><span class="w" id="mwBAU"> </span><span class="nv" id="mwBAY">$squarer</span><span class="w" id="mwBAc"> </span><span class="o" id="mwBAg">=</span><span class="w" id="mwBAk"> </span><span class="k" id="mwBAo">sub</span><span class="w" id="mwBAs"> </span><span class="p" id="mwBAw">{</span><span class="w" id="mwBA0"> </span><span class="k" id="mwBA4">my</span><span class="w" id="mwBA8"> </span><span class="nv" id="mwBBA">$x</span><span class="w" id="mwBBE"> </span><span class="o" id="mwBBI">=</span><span class="w" id="mwBBM"> </span><span class="nb" id="mwBBQ">shift</span><span class="p" id="mwBBU">;</span><span class="w" id="mwBBY"> </span><span class="nv" id="mwBBc">$x</span><span class="w" id="mwBBg"> </span><span class="o" id="mwBBk">*</span><span class="w" id="mwBBo"> </span><span class="nv" id="mwBBs">$x</span><span class="w" id="mwBBw"> </span><span class="p" id="mwBB0">};</span><span class="w" id="mwBB4"> </span><span class="c1" id="mwBB8"># 2. assigned to a variable</span> <span class="k" id="mwBCA">sub</span><span class="w" id="mwBCE"> </span><span class="nf" id="mwBCI">curry</span><span class="w" id="mwBCM"> </span><span class="p" id="mwBCQ">{</span> <span class="w" id="mwBCU"> </span><span class="k" id="mwBCY">my</span><span class="w" id="mwBCc"> </span><span class="p" id="mwBCg">(</span><span class="nv" id="mwBCk">$sub</span><span class="p" id="mwBCo">,</span><span class="w" id="mwBCs"> </span><span class="nv" id="mwBCw">@args</span><span class="p" id="mwBC0">)</span><span class="w" id="mwBC4"> </span><span class="o" id="mwBC8">=</span><span class="w" id="mwBDA"> </span><span class="nv" id="mwBDE">@_</span><span class="p" id="mwBDI">;</span> <span class="w" id="mwBDM"> </span><span class="k" id="mwBDQ">return</span><span class="w" id="mwBDU"> </span><span class="k" id="mwBDY">sub</span><span class="w" id="mwBDc"> </span><span class="p" id="mwBDg">{</span><span class="w" id="mwBDk"> </span><span class="nv" id="mwBDo">$sub</span><span class="o" id="mwBDs">-></span><span class="p" id="mwBDw">(</span><span class="nv" id="mwBD0">@args</span><span class="p" id="mwBD4">,</span><span class="w" id="mwBD8"> </span><span class="nv" id="mwBEA">@_</span><span class="p" id="mwBEE">)</span><span class="w" id="mwBEI"> </span><span class="p" id="mwBEM">};</span><span class="w" id="mwBEQ"> </span><span class="c1" id="mwBEU"># 3. as a return value of another function</span> <span class="p" id="mwBEY">}</span> <span class="c1" id="mwBEc"># example of currying in Perl programming</span> <span class="k" id="mwBEg">sub</span><span class="w" id="mwBEk"> </span><span class="nf" id="mwBEo">sum</span><span class="w" id="mwBEs"> </span><span class="p" id="mwBEw">{</span><span class="w" id="mwBE0"> </span><span class="k" id="mwBE4">my</span><span class="w" id="mwBE8"> </span><span class="nv" id="mwBFA">$tot</span><span class="w" id="mwBFE"> </span><span class="o" id="mwBFI">=</span><span class="w" id="mwBFM"> </span><span class="mi" id="mwBFQ">0</span><span class="p" id="mwBFU">;</span><span class="w" id="mwBFY"> </span><span class="nv" id="mwBFc">$tot</span><span class="w" id="mwBFg"> </span><span class="o" id="mwBFk">+=</span><span class="w" id="mwBFo"> </span><span class="nv" id="mwBFs">$_</span><span class="w" id="mwBFw"> </span><span class="k" id="mwBF0">for</span><span class="w" id="mwBF4"> </span><span class="nv" id="mwBF8">@_</span><span class="p" id="mwBGA">;</span><span class="w" id="mwBGE"> </span><span class="nv" id="mwBGI">$tot</span><span class="w" id="mwBGM"> </span><span class="p" id="mwBGQ">}</span><span class="w" id="mwBGU"> </span><span class="c1" id="mwBGY"># returns the sum of its arguments</span> <span class="k" id="mwBGc">my</span><span class="w" id="mwBGg"> </span><span class="nv" id="mwBGk">$curried</span><span class="w" id="mwBGo"> </span><span class="o" id="mwBGs">=</span><span class="w" id="mwBGw"> </span><span class="n" id="mwBG0">curry</span><span class="w" id="mwBG4"> </span><span class="o" id="mwBG8">\&</span><span class="n" id="mwBHA">sum</span><span class="p" id="mwBHE">,</span><span class="w" id="mwBHI"> </span><span class="mi" id="mwBHM">5</span><span class="p" id="mwBHQ">,</span><span class="w" id="mwBHU"> </span><span class="mi" id="mwBHY">7</span><span class="p" id="mwBHc">,</span><span class="w" id="mwBHg"> </span><span class="mi" id="mwBHk">9</span><span class="p" id="mwBHo">;</span> <span class="k" id="mwBHs">print</span><span class="w" id="mwBHw"> </span><span class="nv" id="mwBH0">$curried</span><span class="o" id="mwBH4">-></span><span class="p" id="mwBH8">(</span><span class="mi" id="mwBIA">1</span><span class="p" id="mwBIE">,</span><span class="mi" id="mwBII">2</span><span class="p" id="mwBIM">,</span><span class="mi" id="mwBIQ">3</span><span class="p" id="mwBIU">),</span><span class="w" id="mwBIY"> </span><span class="s" id="mwBIc">"\n"</span><span class="p" id="mwBIg">;</span><span class="w" id="mwBIk"> </span><span class="c1" id="mwBIo"># prints 27 ( = 5 + 7 + 9 + 1 + 2 + 3 )</span>Other constructs take bare blocks as arguments, which serve a function similar to lambda functions of one parameter, but do not have the same parameter-passing convention as functions -- @_ is not set.
<span id="mwBI0"></span><span class="k" id="mwBI4">my</span><span class="w" id="mwBI8"> </span><span class="nv" id="mwBJA">@squares</span><span class="w" id="mwBJE"> </span><span class="o" id="mwBJI">=</span><span class="w" id="mwBJM"> </span><span class="nb" id="mwBJQ">map</span><span class="w" id="mwBJU"> </span><span class="p" id="mwBJY">{</span><span class="w" id="mwBJc"> </span><span class="nv" id="mwBJg">$_</span><span class="w" id="mwBJk"> </span><span class="o" id="mwBJo">*</span><span class="w" id="mwBJs"> </span><span class="nv" id="mwBJw">$_</span><span class="w" id="mwBJ0"> </span><span class="p" id="mwBJ4">}</span><span class="w" id="mwBJ8"> </span><span class="mi" id="mwBKA">1</span><span class="o" id="mwBKE">..</span><span class="mi" id="mwBKI">10</span><span class="p" id="mwBKM">;</span><span class="w" id="mwBKQ"> </span><span class="c1" id="mwBKU"># map and grep don't use the 'sub' keyword</span> <span class="k" id="mwBKY">my</span><span class="w" id="mwBKc"> </span><span class="nv" id="mwBKg">@square2</span><span class="w" id="mwBKk"> </span><span class="o" id="mwBKo">=</span><span class="w" id="mwBKs"> </span><span class="nb" id="mwBKw">map</span><span class="w" id="mwBK0"> </span><span class="nv" id="mwBK4">$_</span><span class="w" id="mwBK8"> </span><span class="o" id="mwBLA">*</span><span class="w" id="mwBLE"> </span><span class="nv" id="mwBLI">$_</span><span class="p" id="mwBLM">,</span><span class="w" id="mwBLQ"> </span><span class="mi" id="mwBLU">1</span><span class="o" id="mwBLY">..</span><span class="mi" id="mwBLc">10</span><span class="p" id="mwBLg">;</span><span class="w" id="mwBLk"> </span><span class="c1" id="mwBLo"># braces unneeded for one expression</span> <span class="k" id="mwBLs">my</span><span class="w" id="mwBLw"> </span><span class="nv" id="mwBL0">@bad_example</span><span class="w" id="mwBL4"> </span><span class="o" id="mwBL8">=</span><span class="w" id="mwBMA"> </span><span class="nb" id="mwBME">map</span><span class="w" id="mwBMI"> </span><span class="p" id="mwBMM">{</span><span class="w" id="mwBMQ"> </span><span class="k" id="mwBMU">print</span><span class="w" id="mwBMY"> </span><span class="k" id="mwBMc">for</span><span class="w" id="mwBMg"> </span><span class="nv" id="mwBMk">@_</span><span class="w" id="mwBMo"> </span><span class="p" id="mwBMs">}</span><span class="w" id="mwBMw"> </span><span class="mi" id="mwBM0">1</span><span class="o" id="mwBM4">..</span><span class="mi" id="mwBM8">10</span><span class="p" id="mwBNA">;</span><span class="w" id="mwBNE"> </span><span class="c1" id="mwBNI"># values not passed like normal Perl function</span>Regular expressions
The Perl language includes a specialized syntax for writing regular expressions (RE, or regexes), and the interpreter contains an engine for matching strings to regular expressions. The regular-expression engine uses a backtracking algorithm, extending its capabilities from simple pattern matching to string capture and substitution. The regular-expression engine is derived from regex written by Henry Spencer.
The Perl regular-expression syntax was originally taken from Unix Version 8 regular expressions. However, it diverged before the first release of Perl and has since grown to include far more features. Many other languages and applications are now adopting Perl Compatible Regular Expressions over POSIX regular expressions, such as PHP, Ruby, Java, Microsoft's .NET Framework, and the Apache HTTP server.
Regular-expression syntax is extremely compact, owing to history. The first regular-expression dialects were only slightly more expressive than globs, and the syntax was designed so that an expression would resemble the text that it matches. This meant using no more than a single punctuation character or a pair of delimiting characters to express the few supported assertions. Over time, the expressiveness of regular expressions grew tremendously, but the syntax design was never revised and continues to rely on punctuation. As a result, regular expressions can be cryptic and extremely dense.
Uses
The m// (match) operator introduces a regular-expression match. (If it is delimited by slashes, as in all of the examples here, the leading m may be omitted for brevity. If the m is present, as in all of the following examples, other delimiters can be used in place of slashes.) In the simplest case, an expression such as
<span id="mwBPA"></span><span class="nv" id="mwBPE">$x</span><span class="w" id="mwBPI"> </span><span class="o" id="mwBPM">=~</span><span class="sr" id="mwBPQ"> /abc/</span><span class="p" id="mwBPU">;</span>
evaluates to true if and only if the string $x matches the regular expression abc.
The s/// (substitute) operator, on the other hand, specifies a search-and-replace operation:
<span id="mwBP4"></span><span class="nv" id="mwBP8">$x</span><span class="w" id="mwBQA"> </span><span class="o" id="mwBQE">=~</span><span class="w" id="mwBQI"> </span><span class="sr" id="mwBQM">s/abc/aBc/</span><span class="p" id="mwBQQ">;</span><span class="w" id="mwBQU"> </span><span class="c1" id="mwBQY"># upcase the b</span>
Another use of regular expressions is to specify delimiters for the split function:
<span id="mwBQs"></span><span class="nv" id="mwBQw">@words</span><span class="w" id="mwBQ0"> </span><span class="o" id="mwBQ4">=</span><span class="w" id="mwBQ8"> </span><span class="nb" id="mwBRA">split</span><span class="w" id="mwBRE"> </span><span class="sr" id="mwBRI">/,/</span><span class="p" id="mwBRM">,</span><span class="w" id="mwBRQ"> </span><span class="nv" id="mwBRU">$line</span><span class="p" id="mwBRY">;</span>
The split function creates a list of the parts of the string that are separated by what matches the regular expression. In this example, a line is divided into a list of its own comma-separated parts, and this list is then assigned to the @words array.
Syntax
Modifiers
Perl regular expressions can take modifiers. These are single-letter suffixes that modify the meaning of the expression:
<span id="mwBSA"></span><span class="nv" id="mwBSE">$x</span><span class="w" id="mwBSI"> </span><span class="o" id="mwBSM">=~</span><span class="sr" id="mwBSQ"> /abc/i</span><span class="p" id="mwBSU">;</span><span class="w" id="mwBSY"> </span><span class="c1" id="mwBSc"># case-insensitive pattern match</span> <span class="nv" id="mwBSg">$x</span><span class="w" id="mwBSk"> </span><span class="o" id="mwBSo">=~</span><span class="w" id="mwBSs"> </span><span class="sr" id="mwBSw">s/abc/aBc/g</span><span class="p" id="mwBS0">;</span><span class="w" id="mwBS4"> </span><span class="c1" id="mwBS8"># global search and replace</span>
Because the compact syntax of regular expressions can make them dense and cryptic, the /x modifier was added in Perl to help programmers write more-legible regular expressions. It allows programmers to place whitespace and comments inside regular expressions:
<span id="mwBTU"></span><span class="nv" id="mwBTY">$x</span><span class="w" id="mwBTc"> </span><span class="o" id="mwBTg">=~</span><span class="sr" id="mwBTk"> /</span> <span class="sr" id="mwBTo"> a # match 'a'</span> <span class="sr" id="mwBTs"> . # followed by any character</span> <span class="sr" id="mwBTw"> c # then followed by the 'c' character</span> <span class="sr" id="mwBT0"> /x</span><span class="p" id="mwBT4">;</span>
Capturing
Portions of a regular expression may be enclosed in parentheses; corresponding portions of a matching string are captured. Captured strings are assigned to the sequential built-in variables $1, $2, $3, …, and a list of captured strings is returned as the value of the match.
<span id="mwBUU"></span><span class="nv" id="mwBUY">$x</span><span class="w" id="mwBUc"> </span><span class="o" id="mwBUg">=~</span><span class="sr" id="mwBUk"> /a(.)c/</span><span class="p" id="mwBUo">;</span><span class="w" id="mwBUs"> </span><span class="c1" id="mwBUw"># capture the character between 'a' and 'c'</span>
Captured strings $1, $2, $3, … can be used later in the code.
Perl regular expressions also allow built-in or user-defined functions to apply to the captured match, by using the /e modifier:
<span id="mwBVM"></span><span class="nv" id="mwBVQ">$x</span><span class="w" id="mwBVU"> </span><span class="o" id="mwBVY">=</span><span class="w" id="mwBVc"> </span><span class="s" id="mwBVg">"Oranges"</span><span class="p" id="mwBVk">;</span> <span class="nv" id="mwBVo">$x</span><span class="w" id="mwBVs"> </span><span class="o" id="mwBVw">=~</span><span class="w" id="mwBV0"> </span><span class="sr" id="mwBV4">s/(ge)/uc($1)/e</span><span class="p" id="mwBV8">;</span><span class="w" id="mwBWA"> </span><span class="c1" id="mwBWE"># OranGEs</span> <span class="nv" id="mwBWI">$x</span><span class="w" id="mwBWM"> </span><span class="o" id="mwBWQ">.=</span><span class="w" id="mwBWU"> </span><span class="nv" id="mwBWY">$1</span><span class="p" id="mwBWc">;</span><span class="w" id="mwBWg"> </span><span class="c1" id="mwBWk"># append $x with the contents of the match in the previous statement: OranGEsge</span>
Objects
There are many ways to write object-oriented code in Perl. The most basic is using "blessed" references. This works by identifying a reference of any type as belonging to a given package, and the package provides the methods for the blessed reference. For example, a two-dimensional point could be defined this way:
<span id="mwBXM"></span><span class="k" id="mwBXQ">sub</span><span class="w" id="mwBXU"> </span><span class="nf" id="mwBXY">Point</span><span class="p" id="mwBXc">::new {</span> <span class="w" id="mwBXg"> </span><span class="c1" id="mwBXk"># Here, Point->new(4, 5) will result in $class being 'Point'.</span> <span class="w" id="mwBXo"> </span><span class="c1" id="mwBXs"># It's a variable to support subclassing (see the perloop manpage).</span> <span class="w" id="mwBXw"> </span><span class="k" id="mwBX0">my</span><span class="w" id="mwBX4"> </span><span class="p" id="mwBX8">(</span><span class="nv" id="mwBYA">$class</span><span class="p" id="mwBYE">,</span><span class="w" id="mwBYI"> </span><span class="nv" id="mwBYM">$x</span><span class="p" id="mwBYQ">,</span><span class="w" id="mwBYU"> </span><span class="nv" id="mwBYY">$y</span><span class="p" id="mwBYc">)</span><span class="w" id="mwBYg"> </span><span class="o" id="mwBYk">=</span><span class="w" id="mwBYo"> </span><span class="nv" id="mwBYs">@_</span><span class="p" id="mwBYw">;</span> <span class="w" id="mwBY0"> </span><span class="nb" id="mwBY4">bless</span><span class="w" id="mwBY8"> </span><span class="p" id="mwBZA">[</span><span class="nv" id="mwBZE">$x</span><span class="p" id="mwBZI">,</span><span class="w" id="mwBZM"> </span><span class="nv" id="mwBZQ">$y</span><span class="p" id="mwBZU">],</span><span class="w" id="mwBZY"> </span><span class="nv" id="mwBZc">$class</span><span class="p" id="mwBZg">;</span><span class="w" id="mwBZk"> </span><span class="c1" id="mwBZo"># Implicit return</span> <span class="p" id="mwBZs">}</span> <span class="k" id="mwBZw">sub</span><span class="w" id="mwBZ0"> </span><span class="nf" id="mwBZ4">Point</span><span class="p" id="mwBZ8">::distance {</span> <span class="w" id="mwBaA"> </span><span class="k" id="mwBaE">my</span><span class="w" id="mwBaI"> </span><span class="p" id="mwBaM">(</span><span class="nv" id="mwBaQ">$self</span><span class="p" id="mwBaU">,</span><span class="w" id="mwBaY"> </span><span class="nv" id="mwBac">$from</span><span class="p" id="mwBag">)</span><span class="w" id="mwBak"> </span><span class="o" id="mwBao">=</span><span class="w" id="mwBas"> </span><span class="nv" id="mwBaw">@_</span><span class="p" id="mwBa0">;</span> <span class="w" id="mwBa4"> </span><span class="k" id="mwBa8">my</span><span class="w" id="mwBbA"> </span><span class="p" id="mwBbE">(</span><span class="nv" id="mwBbI">$dx</span><span class="p" id="mwBbM">,</span><span class="w" id="mwBbQ"> </span><span class="nv" id="mwBbU">$dy</span><span class="p" id="mwBbY">)</span><span class="w" id="mwBbc"> </span><span class="o" id="mwBbg">=</span><span class="w" id="mwBbk"> </span><span class="p" id="mwBbo">(</span><span class="nv" id="mwBbs">$$self</span><span class="p" id="mwBbw">[</span><span class="mi" id="mwBb0">0</span><span class="p" id="mwBb4">]</span><span class="w" id="mwBb8"> </span><span class="o" id="mwBcA">-</span><span class="w" id="mwBcE"> </span><span class="nv" id="mwBcI">$$from</span><span class="p" id="mwBcM">[</span><span class="mi" id="mwBcQ">0</span><span class="p" id="mwBcU">],</span><span class="w" id="mwBcY"> </span><span class="nv" id="mwBcc">$$self</span><span class="p" id="mwBcg">[</span><span class="mi" id="mwBck">1</span><span class="p" id="mwBco">]</span><span class="w" id="mwBcs"> </span><span class="o" id="mwBcw">-</span><span class="w" id="mwBc0"> </span><span class="nv" id="mwBc4">$$from</span><span class="p" id="mwBc8">[</span><span class="mi" id="mwBdA">1</span><span class="p" id="mwBdE">]);</span> <span class="w" id="mwBdI"> </span><span class="nb" id="mwBdM">sqrt</span><span class="p" id="mwBdQ">(</span><span class="nv" id="mwBdU">$dx</span><span class="w" id="mwBdY"> </span><span class="o" id="mwBdc">*</span><span class="w" id="mwBdg"> </span><span class="nv" id="mwBdk">$dx</span><span class="w" id="mwBdo"> </span><span class="o" id="mwBds">+</span><span class="w" id="mwBdw"> </span><span class="nv" id="mwBd0">$dy</span><span class="w" id="mwBd4"> </span><span class="o" id="mwBd8">*</span><span class="w" id="mwBeA"> </span><span class="nv" id="mwBeE">$dy</span><span class="p" id="mwBeI">);</span> <span class="p" id="mwBeM">}</span>This class can be used by invoking new() to construct instances, and invoking distance on those instances.
<span id="mwBek"></span><span class="k" id="mwBeo">my</span><span class="w" id="mwBes"> </span><span class="nv" id="mwBew">$p1</span><span class="w" id="mwBe0"> </span><span class="o" id="mwBe4">=</span><span class="w" id="mwBe8"> </span><span class="nn" id="mwBfA">Point</span><span class="o" id="mwBfE">-></span><span class="k" id="mwBfI">new</span><span class="p" id="mwBfM">(</span><span class="mi" id="mwBfQ">3</span><span class="p" id="mwBfU">,</span><span class="w" id="mwBfY"> </span><span class="mi" id="mwBfc">4</span><span class="p" id="mwBfg">);</span> <span class="k" id="mwBfk">my</span><span class="w" id="mwBfo"> </span><span class="nv" id="mwBfs">$p2</span><span class="w" id="mwBfw"> </span><span class="o" id="mwBf0">=</span><span class="w" id="mwBf4"> </span><span class="nn" id="mwBf8">Point</span><span class="o" id="mwBgA">-></span><span class="k" id="mwBgE">new</span><span class="p" id="mwBgI">(</span><span class="mi" id="mwBgM">0</span><span class="p" id="mwBgQ">,</span><span class="w" id="mwBgU"> </span><span class="mi" id="mwBgY">0</span><span class="p" id="mwBgc">);</span> <span class="k" id="mwBgg">print</span><span class="w" id="mwBgk"> </span><span class="nv" id="mwBgo">$p1</span><span class="o" id="mwBgs">-></span><span class="n" id="mwBgw">distance</span><span class="p" id="mwBg0">(</span><span class="nv" id="mwBg4">$p2</span><span class="p" id="mwBg8">);</span><span class="w" id="mwBhA"> </span><span class="c1" id="mwBhE"># Prints 5</span>
Many modern Perl applications use the Moose object system. Moose is built on top of Class::MOP, a meta-object protocol, providing complete introspection for all Moose-using classes. Thus you can ask classes about their attributes, parents, children, methods, etc. using a simple API.
Moose classes:
- A class has zero or more attributes.
- A class has zero or more methods.
- A class has zero or more superclasses (aka parent classes). A class inherits from its superclass(es).
- A class does zero or more roles, which add the ability to add pre-defined functionality to classes without subclassing.
- A class has a constructor and a destructor.
- A class has a metaclass.
- A class has zero or more method modifiers. These modifiers can apply to its own methods, methods that are inherited from its ancestors, or methods that are provided by roles.
Moose roles:
- A role is something that a class does, somewhat like mixins or interfaces in other object-oriented programming languages. Unlike mixins and interfaces, roles can be applied to individual object instances.
- A role has zero or more attributes.
- A role has zero or more methods.
- A role has zero or more method modifiers.
- A role has zero or more required methods.
Examples
An example of a class written using the MooseX::Declare extension to Moose:
<span id="mwBjE"></span><span class="k" id="mwBjI">use</span> <span class="n" id="mwBjM">MooseX::Declare</span>; <span class="k" id="mwBjQ">class</span> <span class="n" id="mwBjU">Point3D</span> <span class="n" id="mwBjY">extends</span> <span class="n" id="mwBjc">Point</span> { <span class="k" id="mwBjg">has</span> <span class="s" id="mwBjk">'z'</span> => (<span class="nb" id="mwBjo">isa</span> => <span class="s" id="mwBjs">'Num'</span>, <span class="k" id="mwBjw">is</span> => <span class="s" id="mwBj0">'rw'</span>); <span class="nb" id="mwBj4">after</span> <span class="n" id="mwBj8">clear</span> { <span class="nv" id="mwBkA">$self-</span>><span class="nb" id="mwBkE">z</span>(<span class="mi" id="mwBkI">0</span>); } <span class="k" id="mwBkM">method</span> <span class="n" id="mwBkQ">set_to</span> (<span class="nb" id="mwBkU">Num</span> <span class="nv" id="mwBkY">$x</span>, <span class="nb" id="mwBkc">Num</span> <span class="nv" id="mwBkg">$y</span>, <span class="nb" id="mwBkk">Num</span> <span class="nv" id="mwBko">$z</span>) { <span class="nv" id="mwBks">$self-</span>><span class="nb" id="mwBkw">x</span>(<span class="nv" id="mwBk0">$x</span>); <span class="nv" id="mwBk4">$self-</span>><span class="n" id="mwBk8">y</span>(<span class="nv" id="mwBlA">$y</span>); <span class="nv" id="mwBlE">$self-</span>><span class="nb" id="mwBlI">z</span>(<span class="nv" id="mwBlM">$z</span>); } }This is a class named Point3D that extends another class named Point explained in Moose examples. It adds to its base class a new attribute z, redefines the method set_to and extends the method clear.

