Perl Programming Documentation
Perl 5 version 26.1 documentation
perlop - Perl operators and precedence
In Perl, the operator determines what operation is performed,
independent of the type of the operands. For example
This is in contrast to many other dynamic languages, where the
operation is determined by the type of the first argument. It also
means that Perl has two versions of some operators, one for numeric
and one for string comparison. For example
There are a few exceptions though:
Operator Precedence and Associativity
Operator precedence and associativity work in Perl more or less like they do in mathematics.
Operator precedence means some operators are evaluated before
others. For example, in
Operator associativity defines what happens if a sequence of the
same operators is used one after another: whether the evaluator will
evaluate the left operations first, or the right first. For example, in
Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Operators borrowed from C keep the same precedence relationship with each other, even where C's precedence is slightly screwy. (This makes learning Perl easier for C folks.) With very few exceptions, these all operate on scalar values only, not array values.
In the following sections, these operators are covered in detail, in the same order in which they appear in the table above.
Many operators can be overloaded for objects. See overload.
Terms and List Operators (Leftward)
A TERM has the highest precedence in Perl. They include variables, quote and quote-like operators, any expression in parentheses, and any function whose arguments are parenthesized. Actually, there aren't really functions in this sense, just list operators and unary operators behaving as functions because you put parentheses around the arguments. These are all documented in perlfunc.
If any list operator (
In the absence of parentheses, the precedence of list operators such as
the commas on the right of the
Also note that
probably doesn't do what you expect at first glance. The parentheses
enclose the argument list for
To do what you meant properly, you must write:
See Named Unary Operators for more discussion of this.
The Arrow Operator
Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and the left side must be either an object (a blessed reference) or a class name (that is, a package name). See perlobj.
The dereferencing cases (as opposed to method-calling cases) are
somewhat extended by the
Auto-increment and Auto-decrement
Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behavior. Avoid statements like:
Perl will not guarantee what the result of the above statements is.
The auto-increment operator has a little extra builtin magic to it. If
you increment a variable that is numeric, or that has ever been used in
a numeric context, you get a normal increment. If, however, the
variable has been used in only string contexts since it was set, and
has a value that is not the empty string and matches the pattern
The auto-decrement operator is not magical.
Note that certain exponentiation expressions are ill-defined:
Symbolic Unary Operators
When complementing strings, if all characters have ordinal values under
256, then their complements will, also. But if they do not, all
characters will be in either 32- or 64-bit complements, depending on your
architecture. So for example,
If the experimental "bitwise" feature is enabled via
If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time. Note that this means that its contents will be interpolated twice, so
is not ok, as the regex engine will end up trying to compile the
Either way, the implementation isn't going to generate results larger than the size of the integer type Perl was built with (32 bits or 64 bits).
Shifting by negative number of bits means the reverse shift: left shift becomes right shift, right shift becomes left shift. This is unlike in C, where negative shift is undefined.
Shifting by more bits than the size of the integers means most of the
time zero (all bits fall off), except that under
but that is completely accidental.
If you get tired of being subject to your platform's native integers,
Named Unary Operators
The various named unary operators are treated as functions with one argument, with optional parentheses.
If any list operator (
Regarding precedence, the filetest operators, like
See also Terms and List Operators (Leftward).
Perl operators that return true or false generally return values
that can be safely used as numbers. For example, the relational
operators in this section and the equality operators in the next
For case-insensitive comparisions, look at the fc case-folding function, available in Perl v5.16 or later:
First available in Perl 5.10.1 (the 5.10.0 version behaved differently),
It is also unique in that all other Perl operators impose a context (usually string or numeric context) on their operands, autoconverting those operands to those imposed contexts. In contrast, smartmatch infers contexts from the actual types of its operands and uses that type information to select a suitable comparison mechanism.
The behavior of a smartmatch depends on what type of things its arguments are, as determined by the following table. The first row of the table whose types apply determines the smartmatch behavior. Because what actually happens is mostly determined by the type of the second operand, the table is sorted on the right operand instead of on the left.
Right operand is a Regexp:
The smartmatch implicitly dereferences any non-blessed hash or array
reference, so the
The "like" code entry is not always an exact rendition. For example, the
smartmatch operator short-circuits whenever possible, but
Unlike most operators, the smartmatch operator knows to treat
Each operand is considered in a modified scalar context, the modification being that array and hash variables are passed by reference to the operator, which implicitly dereferences them. Both elements of each pair are the same:
Two arrays smartmatch if each element in the first array smartmatches (that is, is "in") the corresponding element in the second array, recursively.
Because the smartmatch operator recurses on nested arrays, this will still report that "red" is in the array.
If two arrays smartmatch each other, then they are deep copies of each others' values, as this example reports:
If you were to set
Smartmatching one hash against another reports whether both contain the same keys, no more and no less. This could be used to see whether two records have the same field names, without caring what values those fields might have. For example:
However, this only does what you mean if
The smartmatch operator is most often used as the implicit operator of a
Smartmatching of Objects
To avoid relying on an object's underlying representation, if the
smartmatch's right operand is an object that doesn't overload
However, you can change the way an object is smartmatched by overloading
Using an object as the left operand is allowed, although not very useful.
Smartmatching rules take precedence over overloading, so even if the
object in the left operand has smartmatch overloading, this will be
ignored. A left operand that is a non-overloaded object falls back on a
string or numeric comparison of whatever the
does not invoke the overload method with
For example, this reports that the handle smells IOish (but please don't really do this!):
That's because it treats
If the experimental "bitwise" feature is enabled via
Bitwise Or and Exclusive Or
Although no warning is currently raised, the results are not well defined when these operations are performed on operands that aren't either numbers (see Integer Arithmetic) nor bitstrings (see Bitwise String Operators).
If the experimental "bitwise" feature is enabled via
C-style Logical And
C-style Logical Or
Although it has no direct equivalent in C, Perl's
In particular, this means that you shouldn't use this for selecting between two aggregates for assignment:
As alternatives to
With the C-style operators that would have been written like this:
It would be even more readable to write that this way:
The range operator also works on strings, using the magical auto-increment, see below.
In scalar context,
The right operand is not evaluated while the operator is in the
"false" state, and the left operand is not evaluated while the
operator is in the "true" state. The precedence is a little lower
than || and &&. The value returned is either the empty string for
false, or a sequence number (beginning with 1) for true. The sequence
number is reset for each range encountered. The final sequence number
in a range has the string
If either operand of scalar
To be pedantic, the comparison is actually
As a scalar operator:
Here's a simple example to illustrate the difference between the two range operators:
This program will print only the line containing "Bar". If
the range operator is changed to
And now some examples as a list operator:
The range operator (in list context) makes use of the magical auto-increment algorithm if the operands are strings. You can say
to get all normal letters of the English alphabet, or
to get a hexadecimal digit, or
to get dates with leading zeros.
If the final value specified is not in the sequence that the magical increment would produce, the sequence goes until the next value would be longer than the final value specified.
As of Perl 5.26, the list-context range operator on strings works as expected in the scope of use feature 'unicode_strings . In previous versions, and outside the scope of that feature, it exhibits The Unicode Bug in perlunicode: its behavior depends on the internal encoding of the range endpoint.
If the initial value specified isn't part of a magical increment
sequence (that is, a non-empty string matching
To get the 25 traditional lowercase Greek letters, including both sigmas, you could use this instead:
However, because there are many other lowercase Greek characters than
just those, to match lowercase Greek characters in a regular expression,
you could use the pattern
Because each operand is evaluated in integer form,
Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected.
The operator may be assigned to if both the 2nd and 3rd arguments are legal lvalues (meaning that you can assign to them):
Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this:
Really means this:
Rather than this:
That should probably be written more simply as:
Assignment operators work as in C. That is,
is equivalent to
although without duplicating any side effects that dereferencing the lvalue
might trigger, such as from
Although these are grouped by family, they all have the precedence of assignment. These combined assignment operators can only operate on scalars, whereas the ordinary assignment operator can assign to arrays, hashes, lists and even references. (See Context and List value constructors in perldata, and Assigning to References in perlref.)
Unlike in C, the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this:
Although as of 5.14, that can be also be accomplished this way:
is equivalent to
Similarly, a list assignment in list context produces the list of lvalues assigned to, and a list assignment in scalar context returns the number of elements produced by the expression on the right hand side of the assignment.
The three dotted bitwise assignment operators (
In list context, it's just the list argument separator, and inserts both its arguments into the list. These arguments are also evaluated from left to right.
is equivalent to:
It is NOT:
The special quoting behavior ignores precedence, and hence may apply to part of the left operand:
List Operators (Rightward)
On the right side of a list operator, the comma has very low precedence,
such that it controls all comma-separated expressions found there.
The only operators with lower precedence are the logical operators
However, some people find that code harder to read than writing it with parentheses:
in which case you might as well just use the more customary
See also discussion of list operators in Terms and List Operators (Leftward).
Logical or and Exclusive Or
This means that it short-circuits: the right expression is evaluated
only if the left expression is false. Due to its precedence, you must
be careful to avoid using it as replacement for the
However, when it's a list-context assignment and you're trying to use
Then again, you could always use parentheses.
There is no low precedence operator for defined-OR.
C Operators Missing From Perl
Here is what C has that Perl doesn't:
Quote and Quote-like Operators
While we usually think of quotes as literal values, in Perl they
function as operators, providing various kinds of interpolating and
pattern matching capabilities. Perl provides customary quote characters
for these behaviors, but also provides a way for you to choose your
quote character for any of them. In the following table, a
Non-bracketing delimiters use the same character fore and aft, but the four sorts of ASCII brackets (round, angle, square, curly) all nest, which means that
is the same as
Note, however, that this does not always work for quoting Perl code:
is a syntax error. The
There can (and in some cases, must) be whitespace between the operator
and the quoting
characters, except when
The cases where whitespace must be used are when the quoting character
is a word character (meaning it matches
The following escape sequences are available in constructs that interpolate, and in transliterations:
NOTE: Unlike C and other languages, Perl has no
The following escape sequences are available in constructs that interpolate, but not in transliterations.
See quotemeta for the exact definition of characters that
are quoted by
All systems use the virtual
For constructs that do interpolate, variables beginning with "
Interpolating an array or slice interpolates the elements in order,
separated by the value of
For double-quoted strings, the quoting from
is equivalent to
For the pattern of regex operators (
Patterns are subject to an additional level of interpretation as a
regular expression. This is done as a second pass, after variables are
interpolated, so that regular expressions may be incorporated into the
pattern from the variables. If this is not what you want, use
Apart from the behavior described above, Perl does not expand multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, back-quotes do NOT interpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes.
Regexp Quote-Like Operators
Here are the quote-like operators that apply to pattern matching and related activities.
Gory details of parsing quoted constructs
When presented with something that might have several different interpretations, Perl uses the DWIM (that's "Do What I Mean") principle to pick the most probable interpretation. This strategy is so successful that Perl programmers often do not suspect the ambivalence of what they write. But from time to time, Perl's notions differ substantially from what the author honestly meant.
This section hopes to clarify how Perl handles quoted constructs. Although the most common reason to learn this is to unravel labyrinthine regular expressions, because the initial steps of parsing are the same for all quoting operators, they are all discussed together.
The most important Perl parsing rule is the first one discussed below: when processing a quoted construct, Perl first finds the end of that construct, then interprets its contents. If you understand this rule, you may skip the rest of this section on the first reading. The other rules are likely to contradict the user's expectations much less frequently than this first one.
Some passes discussed below are performed concurrently, but because their results are the same, we consider them individually. For different quoting constructs, Perl performs different numbers of passes, from one to four, but these passes are always performed in the same order.
There are several I/O operators you should know about.
A string enclosed by backticks (grave accents) first undergoes
double-quote interpolation. It is then interpreted as an external
command, and the output of that command is the value of the
backtick string, like in a shell. In scalar context, a single string
consisting of all output is returned. In list context, a list of
values is returned, one per line of output. (You can set
In scalar context, evaluating a filehandle in angle brackets yields
the next line from that file (the newline, if any, included), or
Ordinarily you must assign the returned value to a variable, but
there is one situation where an automatic assignment happens. If
and only if the input symbol is the only thing inside the conditional
The following lines are equivalent:
This also behaves similarly, but assigns to a lexical variable
instead of to
In these loop constructs, the assigned value (whether assignment
is automatic or explicit) is then tested to see whether it is
defined. The defined test avoids problems where the line has a string
value that would be treated as false by Perl; for example a "" or
The filehandles STDIN, STDOUT, and STDERR are predefined. (The
The null filehandle
is equivalent to the following Perl-like pseudo code:
except that it isn't so cumbersome to say, and will actually work.
It really does shift the
Since the null filehandle uses the two argument form of open it interprets special characters, so if you have a script like this:
and call it with
Using double angle brackets inside of a while causes the open to use the
three argument form (with the second argument being
You can modify
If you want to set
You can even set them to pipe commands. For example, this automatically filters compressed arguments through gzip:
If you want to pass switches into your script, you can use one of the
If what the angle brackets contain is a simple scalar variable (for example,
If what's within the angle brackets is neither a filehandle nor a simple
scalar variable containing a filehandle name, typeglob, or typeglob
reference, it is interpreted as a filename pattern to be globbed, and
either a list of filenames or the next filename in the list is returned,
depending on context. This distinction is determined on syntactic
grounds alone. That means
One level of double-quote interpretation is done first, but you can't
is roughly equivalent to:
except that the globbing is actually done internally using the standard
A (file)glob evaluates its (embedded) argument only when it is
starting a new list. All values must be read before it will start
over. In list context, this isn't important because you automatically
get them all anyway. However, in scalar context the operator returns
the next value each time it's called, or
because the latter will alternate between returning a filename and returning false.
If you're trying to do variable interpolation, it's definitely better
to use the
Like C, Perl does a certain amount of expression evaluation at compile time whenever it determines that all arguments to an operator are static and have no side effects. In particular, string concatenation happens at compile time between literals that don't do variable substitution. Backslash interpolation also happens at compile time. You can say
and this all reduces to one string internally. Likewise, if you say
the compiler precomputes the number which that expression represents so that the interpreter won't have to.
Perl doesn't officially have a no-op operator, but the bare constants
Bitwise String Operators
Bitstrings of any size may be manipulated by the bitwise operators
If the operands to a binary bitwise op are strings of different sizes, | and ^ ops act as though the shorter operand had additional zero bits on the right, while the & op acts as though the longer operand were truncated to the length of the shorter. The granularity for such extension or truncation is one or more bytes.
If you are intending to manipulate bitstrings, be certain that
you're supplying bitstrings: If an operand is a number, that will imply
a numeric bitwise operation. You may explicitly show which type of
operation you intend by using
This somewhat unpredictable behavior can be avoided with the experimental
"bitwise" feature, new in Perl 5.22. You can enable it via
The assignment variants of these operators (
The behavior of these operators is problematic (and subject to change) if either or both of the strings are encoded in UTF-8 (see Byte and Character Semantics in perlunicode.
See vec for information on how to manipulate individual bits in a bit vector.
By default, Perl assumes that it must do most of its arithmetic in floating point. But by saying
you may tell the compiler to use integer operations (see integer for a detailed explanation) from here to the end of the enclosing BLOCK. An inner BLOCK may countermand this by saying
which lasts until the end of that BLOCK. Note that this doesn't
mean everything is an integer, merely that Perl will use integer
operations for arithmetic, comparison, and bitwise operators. For
example, even under
Used on numbers, the bitwise operators (
Floating-point numbers are only approximations to what a mathematician would call real numbers. There are infinitely more reals than floats, so some corners must be cut. For example:
Testing for exact floating-point equality or inequality is not a good idea. Here's a (relatively expensive) work-around to compare whether two floating-point numbers are equal to a particular number of decimal places. See Knuth, volume II, for a more robust treatment of this topic.
The POSIX module (part of the standard perl distribution) implements
Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.
Or with rationals:
Several modules let you calculate with unlimited or fixed precision (bound only by memory and CPU time). There are also some non-standard modules that provide faster implementations via external C libraries.
Here is a short, but incomplete summary: