Skip to content

Perl Operators

An operator is a symbol that tells the compiler or interpreter to perform a specific mathematical, relational, or logical operation and produce a final result. For example, in the expression 4 + 5, 4 and 5 are operands, and + is the operator.

Perl supports a rich set of operators. Key categories include:

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Logical Operators
  • Assignment Operators
  • Bitwise Operators
  • String Operators
  • Miscellaneous Operators (including Quote-like and Arrow operator)

Let’s explore these operators with examples. Assume my $a = 10; and my $b = 20; for numerical examples, and my $x = "hello"; my $y = "world"; for string examples.

These perform mathematical calculations.

OperatorDescriptionExample (with $a=10, $b=20)
+Addition: Adds values on either side.$a + $b will give 30
-Subtraction: Subtracts the right-hand operand from the left-hand operand.$a - $b will give -10
*Multiplication: Multiplies values on either side.$a * $b will give 200
/Division: Divides the left-hand operand by the right-hand operand.$b / $a will give 2
%Modulus: Divides the left-hand operand by the right-hand operand and returns the remainder.$b % $a will give 0
**Exponentiation: Raises the left operand to the power of the right operand.$a**2 will give 100 (10 to the power 2)

These operators compare two operands and return a boolean value (true or false). Perl has separate sets for numeric and string comparisons.

OperatorDescriptionExample (with $a=10, $b=20)
==Equal to: True if values are numerically equal.($a == $b) is false.
!=Not equal to: True if values are numerically not equal.($a != $b) is true.
<=>Numeric comparison: Returns -1 if left is less than right, 0 if equal, 1 if left is greater than right.($a <=> $b) returns -1.
>Greater than: True if left operand is numerically greater than right.($a > $b) is false.
<Less than: True if left operand is numerically less than right.($a < $b) is true.
>=Greater than or equal to: True if left operand is numerically greater than or equal to right.($a >= $b) is false.
<=Less than or equal to: True if left operand is numerically less than or equal to right.($a <= $b) is true.

Assume my $s1 = "apple"; my $s2 = "banana";

OperatorDescriptionExample
ltLess than: True if left argument is stringwise less than right.($s1 lt $s2) is true.
gtGreater than: True if left argument is stringwise greater than right.($s1 gt $s2) is false.
leLess than or equal to: True if left argument is stringwise less than or equal to right.($s1 le $s2) is true.
geGreater than or equal to: True if left argument is stringwise greater than or equal to right.($s1 ge $s2) is false.
eqEqual to: True if left argument is stringwise equal to right.($s1 eq $s2) is false.
neNot equal to: True if left argument is stringwise not equal to right.($s1 ne $s2) is true.
cmpString comparison: Returns -1, 0, or 1 based on lexicographical comparison (similar to <=> for numbers).($s1 cmp $s2) returns -1.

These operators assign a value to a variable. Most can be combined with other operators for shorthand.

OperatorDescriptionExample (with $a=10)
=Simple assignment: Assigns value from right side to left side operand.my $c = $a + $b; assigns 30 to $c.
+=Add AND assignment: Adds right operand to left, assigns result to left.$c = 5; $c += $a; ($c becomes 15, same as $c = $c + $a).
-=Subtract AND assignment: Subtracts right from left, assigns result to left.$c = 15; $c -= $a; ($c becomes 5, same as $c = $c - $a).
*=Multiply AND assignment: Multiplies left by right, assigns result to left.$c = 2; $c *= $a; ($c becomes 20, same as $c = $c * $a).
/=Divide AND assignment: Divides left by right, assigns result to left.$c = 20; $c /= $a; ($c becomes 2, same as $c = $c / $a).
%=Modulus AND assignment: Takes modulus, assigns result to left.$c = 25; $c %= $a; ($c becomes 5, same as $c = $c % $a).
**=Exponent AND assignment: Raises left to power of right, assigns to left.$c = 2; $c **= 3; ($c becomes 8, same as $c = $c ** 3).
.=String concatenate AND assignment: Concatenates right string to left, assigns to left.my $str = "Hi "; $str .= "Perl"; ($str becomes “Hi Perl”).
x=String repeat AND assignment: Repeats left string by right number, assigns to left.my $str = "-"; $str x= 3; ($str becomes ”---”).

Bitwise operators work on the binary representation of numbers.

Assume $a = 60; (binary 00111100) and $b = 13; (binary 00001101).

OperatorDescriptionExample
&Bitwise AND: Copies a bit to the result if it exists in both operands.($a & $b) gives 12 (binary 00001100).
|Bitwise OR: Copies a bit if it exists in either operand.($a | $b) gives 61 (binary 00111101).
^Bitwise XOR: Copies the bit if it is set in one operand but not both.($a ^ $b) gives 49 (binary 00110001).
~Bitwise NOT (Ones’ Complement): Unary operator, flips all bits.(~$a) gives -61 (in 2’s complement form). Result depends on system’s integer size.
<<Left Shift: Shifts bits of left operand to the left by the number of positions specified by right operand. Fills with zeros.$a << 2 gives 240 (binary 11110000).
>>Right Shift: Shifts bits of left operand to the right. For unsigned numbers, fills with zeros. For signed, behavior can vary (arithmetic vs. logical shift).$a >> 2 gives 15 (binary 00001111).

Logical operators are typically used with boolean values or expressions that evaluate to true/false.

Assume $x is true (e.g., 1) and $y is false (e.g., 0 or undef).

OperatorDescriptionExample
andLogical AND (low precedence): True if both operands are true.($x and $y) is false.
&&Logical AND (higher precedence, C-style): True if both operands are true. Short-circuits.($x && $y) is false.
orLogical OR (low precedence): True if at least one operand is true.($x or $y) is true.
||Logical OR (higher precedence, C-style): True if at least one operand is true. Short-circuits.($x || $y) is true.
notLogical NOT (low precedence): Reverses the logical state of its operand.not $y is true.
!Logical NOT (higher precedence, C-style): Reverses the logical state.!$y is true.
//Defined-Or (since Perl 5.10): Returns the left operand if it’s defined, otherwise returns the right operand. Short-circuits.my $val = undef; my $default = $val // "default_value"; ($default becomes “default_value”).

Short-circuiting: && and || (and //) only evaluate their right operand if necessary. For example, in expr1 && expr2, expr2 is not evaluated if expr1 is false.

Perl provides flexible ways to quote strings and other literals. q{} denotes any pair of balanced delimiters (e.g., q(), q<>, q##).

OperatorDescriptionExample
q{ }Single quotes: Interpolates \\ and \{delimiter} only.q{don't interpolate $var} results in the literal string ‘don’t interpolate $var’.
qq{ }Double quotes: Performs variable and escape sequence interpolation.my $name = "Perl"; qq{Hello, $name!} results in “Hello, Perl!“.
qx{ }Command execution (backticks): Executes the content as a system command and returns its standard output.qx{ls -l} or `ls -l` executes ls -l.
qw{ }Quote words: Splits the content by whitespace into a list of single-quoted words.qw{foo bar baz} is equivalent to ('foo', 'bar', 'baz').
qr{ }Regex quote: Compiles the content as a regular expression and returns a regex object.my $regex = qr/pattern/i;
OperatorDescriptionExample
.String concatenation: Joins two strings."hello" . " " . "world" gives “hello world”.
xString repetition: Repeats the left string operand the number of times specified by the right operand."-" x 3 gives ”---”.
..Range operator: In list context, creates a list of values incrementing from left to right. In scalar context (e.g., in if), it’s a bistable flip-flop operator.List: (1..5) gives (1, 2, 3, 4, 5). Scalar: if ($line_num .. $end_line_num) (flip-flop).
++Auto-increment: Increments an integer value by one. Can be pre- (++$var) or post-increment ($var++).my $i = 5; $i++; ($i becomes 6).
—Auto-decrement: Decrements an integer value by one. Can be pre- (--$var) or post-decrement ($var--).my $i = 5; $i--; ($i becomes 4).
->Arrow operator (infix dereference): Used to dereference references, typically for accessing array/hash elements or calling methods on objects.$array_ref->[0], $hash_ref->{key}, $object->method().

Operator precedence determines the order in which operations are performed in an expression with multiple operators. Parentheses () can be used to explicitly control the order of evaluation. Below is a simplified list from highest to lowest precedence. Refer to perldoc perlop for the complete, authoritative list.

1. Terms and List Operators (leftward): `print`, `qw//` etc.
2. Arrow operator: `->`
3. Auto-increment and auto-decrement: `++`, `--` (nonassoc)
4. Exponentiation: `**` (right assoc)
5. Unary operators: `!`, `~`, `\` (reference), unary `+`, unary `-` (right assoc)
6. Binding operators: `=~`, `!~` (left assoc)
7. Multiplicative: `*`, `/`, `%`, `x` (string repetition) (left assoc)
8. Additive: `+`, `-`, `.` (string concat) (left assoc)
9. Shift operators: `<<`, `>>` (left assoc)
10. Named unary operators: `stat`, `chomp`, etc. (nonassoc)
11. Relational: `<`, `>`, `<=`, `>=`, `lt`, `gt`, `le`, `ge` (nonassoc)
12. Equality: `==`, `!=`, `<=>`, `eq`, `ne`, `cmp` (nonassoc)
13. Bitwise AND: `&` (left assoc)
14. Bitwise OR and XOR: `|`, `^` (left assoc)
15. C-style Logical AND: `&&` (left assoc)
16. C-style Logical OR: `||` (left assoc)
17. Defined-Or: `//` (left assoc)
18. Range operator: `..`, `...` (nonassoc)
19. Conditional (ternary) operator: `? :` (right assoc)
20. Assignment operators: `=`, `+=`, `-=`, `*=`, etc. (right assoc)
21. Comma operator, list separator: `,`, `=>` (left assoc)
22. List operators (rightward): `print` (if on right of comma), etc.
23. Logical NOT (low precedence): `not` (right assoc)
24. Logical AND (low precedence): `and` (left assoc)
25. Logical OR and XOR (low precedence): `or`, `xor` (left assoc)

Understanding precedence is crucial for writing correct and unambiguous Perl code. When in doubt, use parentheses.