Operators

Table 4.3 lists all the Perl operators from highest to lowest precedence and indicates their associativity.

Table 4-3. Perl Associativity and Operators, Listed by Precedence

AssociativityOperators
LeftTerms and list operators (leftward)
Left -> (method call, dereference)
Nonassociative ++ -- (autoincrement, autodecrement)
Right ** (exponentiation)
Right

! ~ \ and unary + and - (logical not, bit-not, reference, unary plus, unary minus)

Left

=~ !~ (matches, doesn’t match)

Left

* / % x (multiply, divide, modulus, string replicate)

Left

+ - . (addition, subtraction, string concatenation)

Left

<< >> (left bit-shift, right bit-shift)

Nonassociative

Named unary operators and file-test operators

Nonassociative

< > <= >= lt gt le ge (less than, greater than, less than or equal to, greater than or equal to, and their string equivalents.

Nonassociative

== != <=> eq ne cmp (equal to, not equal to, signed comparison, and their string equivalents)

Left & (bit-and)
Left | ^ (bit-or, bit-xor)
Left && (logical AND)
Left || (logical OR)
Nonassociative .. &#133; (range)
Right ?: (ternary conditional)
Right

= += -= *= and so on (assignment operators)

Left , => (comma, arrow comma)
NonassociativeList operators (rightward)
Right not (logical not)
Left and (logical and)
Left or xor (logical or, xor)

You can make your expressions clear by using parentheses to group any part of an expression. Anything in parentheses will be evaluated as a single unit within a larger expression.

With very few exceptions, Perl operators act upon scalar values only, not upon list values.

Terms that take highest precedence in Perl include variables, quote and quotelike operators, any expression in parentheses, and any function whose arguments are in parentheses.

A list operator is a function that can take a list of values as its argument. List operators take highest precedence when considering what’s to the left of them. They have considerably lower precedence when looking at their right side, which is the expected result.

Also parsed as high-precedence terms are the do{} and eval{} constructs, as well as subroutine and method calls, the anonymous array and hash composers ([] and {}), and the anonymous subroutine composer sub{}.

A unary operator is a function that takes a single scalar value as its argument. Unary operators have a lower precedence than list operators because they only expect and take one value.

The Arrow Operator

The arrow operator is a dereference operator. It can be used for references to arrays, hashes, code references, or for calling methods on objects. See the discussion of references in Chapter 7.

Unary Operators

Unary ! performs logical negation, that is, “not.” The not operator is a lower-precedence version of !.

Unary - performs arithmetic negation if the operand is numeric. If the operand is an identifier, then a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned.

Unary ~ performs bitwise negation, that is, one’s complement. For example, on a 32-bit machine, ~0xFF is 0xFFFFFF00. If the argument to ~ is a string instead of a number, a string of identical length is returned, but with all the bits of the string complemented.

Unary + has no semantic effect whatsoever, even on strings. It is syntactically useful for separating a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments.

Unary \ creates a reference to whatever follows it (see “References and Complex Data Structures” later in this chapter). Do not confuse this behavior with the behavior of backslash within a string. The \ operator may also be used on a parenthesized list value in a list context, in which case it returns references to each element of the list.

Arithmetic Operators

Binary ** is the exponentiation operator. Note that it binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. Note also that ** has right associativity, so:

$e = 2 ** 3 ** 4;

evaluates to 2 to the 81st power, not 8 to the 4th power.

The * (multiply) and / (divide) operators work exactly as you might expect, multiplying or dividing their two operands. Division is done in floating-point mode, unless integer mode in enabled (via use integer).

The % (modulus) operator converts its operands to integers before finding the remainder according to integer division. For the same operation in floating-point mode, you may prefer to use the fmod() function from the POSIX module (see Chapter 8).

Comparison Operators

Relational operators

Perl has two classes of relational operators. One class operates on numeric values, and the other operates on string values. String comparisons are based on the ASCII collating sequence. Relational operators are nonassociative, so $a < $b < $c is a syntax error.

NumericStringMeaning
> gt Greater than
>= ge Greater than or equal to
< lt Less than
<= le Less than or equal to

Equality operators

The equal and not-equal operators return 1 for true, and "" for false (just as the relational operators do). The <=> and cmp operators return -1 if the left operand is less than the right operand, 0 if they are equal, and +1 if the left operand is greater than the right.

NumericStringMeaning
== eq Equal to
!= ne Not equal to
<=> cmp Comparison, with signed result

Autoincrement and Autodecrement

If placed before a variable, the ++ and -- operators increment or decrement the variable before returning the value, and if placed after, they increment or decrement the variable after returning the value.

Assignment Operators

Perl recognizes the following operators for assigning a value to a variable:

=    **=    +=    *=    &=    <<=    &&=
            -=    /=    |=    >>=    ||=
            .=    %=    ^=
                  x=

Each operator requires a variable on the left side and some expression on the right side. For the simple assignment operator, =, the value of the expression is stored into the designated variable. For the other operators, Perl evaluates the expression:

$var OP= $value

as if it were written:

$var = $var OP $value

except that $var is evaluated only once. For example:

$a += 2; # same as $a = $a + 2

Pattern Match Operators

Binary =~ binds a scalar expression to a pattern match, substitution, or translation. These operations search or modify the string $_ by default.

Binary !~ is just like =~ except the return value is negated in the logical sense. The following expressions are functionally equivalent:

$string !~ /pattern/
not $string =~ /pattern/

See Section 4.6 later in this chapter.

File Test Operators

A file test operator is a unary operator that tests a filename or a filehandle.

OperatorMeaning
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
-x File is executable by effective uid/gid.
-o File is owned by effective uid.
-R File is readable by real uid/gid.
-W File is writable by real uid/gid.
-X File is executable by real uid/gid.
-O File is owned by real uid.
  
-e File exists.
-z File has zero size.
-s File has non-zero size (returns size).
  
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
-p File is a named pipe (FIFO).
-S File is a socket.
-b File is a block special file.
-c File is a character special file.
-t Filehandle is opened to a tty.
  
-u File has setuid bit set.
-g File has setgid bit set.
-k File has sticky bit set.
  
-T File is a text file.
-B File is a binary file (opposite of -T).
  
-M Age of file (at startup) in days since modification.
-A Age of file (at startup) in days since last access.
-C Age of file (at startup) in days since inode change.

Logical Operators

Perl provides the && (logical AND) and || (logical OR) operators. They evaluate from left to right testing the truth of the statement.

ExampleNameResult
$a && $b And

$a if $a is false, $b otherwise

$a || $b Or

$a if $a is true, $b otherwise

For example, an oft-appearing idiom in Perl programs is:

open(FILE, "somefile") || die "Cannot open somefile: $!\n";

In this case, Perl first evaluates the open function. If the value is true (because somefile was successfully opened), the execution of the die function is unnecessary and is skipped.

Perl also provides lower-precedence and and or operators that are more readable.

Bitwise Operators

Perl has bitwise AND, OR, and XOR (exclusive OR) operators: &, |, and ^. These operators work differently on numeric values than they do on strings. If either operand is a number, then both operands are converted to integers, and the bitwise operation is performed between the two integers. If both operands are strings, these operators do bitwise operations between corresponding bits from the two strings.

Miscellaneous Operators

Range operator

The .. range operator is really two different operators depending on the context. In a list context, it returns a list of values counting (by ones) from the left value to the right value.

In a scalar context, .. returns a Boolean value. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, after which the range operator becomes false again. 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 alternate version of this operator, &#133;, does not test the right operand immediately when the operator becomes true; it waits until the next evaluation.

Conditional operator

Ternary ?: is the conditional operator. It works much like an if-then-else statement, but it can safely be embedded within other operations and functions.

                        test_expr ? if_true_expr : if_false_expr

If the test_expr is true, only the if_true_expr is evaluated. Otherwise, only the if_false_expr is evaluated. Either way, the value of the evaluated expression becomes the value of the entire expression.

Comma operator

In a list context, "," is the list argument separator and inserts both its arguments into the list. In scalar context, "," evaluates its left argument, throws that value away, then evaluates its right argument and returns that value.

The => operator is mostly just a synonym for the comma operator. It’s useful for documenting arguments that come in pairs. It also forces any identifier to the left of it to be interpreted as a string.

String operator

The concatenation operator “.” is used to add strings together:

print 'abc' . 'def';        # prints abcdef
print $a . $b;              # concatenates the string values of $a and $b

Binary x is the string repetition operator. In scalar context, it returns a concatenated string consisting of the left operand repeated the number of times specified by the right operand.

print '-' x 80;                           # prints row of dashes
print "\t" x ($tab/8), ' ' x ($tab%8);    # tabs over

In list context, if the left operand is a list in parentheses, the x works as a list replicator rather than a string replicator. This is useful for initializing all the elements of an array of indeterminate length to the same value:

@ones = (1) x 80;           # a list of 80 1s
@ones = (5) x @ones;        # set all elements to 5

Get Perl in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.