Basic Operators
Arithmetic
Arithmetic | Name | Result |
$a + $b | Addition | Sum of $a and $b |
$a * $b | Multiplication | Product of $a and $b |
$a % $b | Modulus | Remainder of $a divided by $b |
$a ** $b | Exponentiation | $a to the power of $b |
String
Example | Name | Result |
$a . “string” | Concatenation | String built from pieces |
“$a string” | Interpolation | String incorporating the value of $a |
$a x $b | Repeat | String in which $a is repeated $b times |
Assignment
The basic assignment operator is “=”: $a = $b. Perl conforms to the C idiom that lvalue operator= expression is evaluated as: lvalue = lvalue operator expression So that $a *= $b is equivalent to $a = $a * $b $a += $b $a = $a + $b This also works for the string concatenation operator: $a .= “\n”
Autoincrement and Autodecrement
The autoincrement and autodecrement operators are special cases of the assignment
operators, which add or subtract 1 from the value of a variable:
++$a, $a++ Autoincrement Add 1 to $a
--$a, $a-- Autodecrement Subtract 1 from $a
Logical
Conditions for truth:
Any string is true except for “” and “0”
Any number is true except for 0
Any reference is true
Any undefined value is false
Example | Name | Result |
---|---|---|
$a && $b | And | True if both $a and $b are true |
$a || $b | Or | $a if $a is true; $b otherwise |
!$a | Not | True if $a is not true |
$a and $b | And | True if both $a and $b are true |
$a or $b | Or | $a if $a is true; $b otherwise |
not $a | Not | True if $a is not true |
Logical operators are often used to “short circuit” expressions, as in:
open(FILE,”< input.dat”) or die “Can’t open file”;
Comparison
Comparison | Numeric | String | Result |
---|---|---|---|
Equal | == | eq | True if $a equal to $b |
Not equal | != | ne | True if $a not equal to $b |
Less than | < | lt | True if $a less than $b |
Greater than | > | gt | True if $a greater than $b |
Less than or equal | <= | le | True if $a not greater than $b |
Comparison | <=> | cmp | 0 if $a and $b equal 1 if $a greater -1 if $b greater |