Perl has numerous operators (over 50 of them!) that perform operations on string and numberic values. Some operators will be familiar from algebra (like "+", to add two numbers together), while others are more esoteric (like the "." string concatenation operator).
The "." operator acts on strings. The "!" operator acts on strings and numbers. The rest act on numbers.
| Operator | Description | Example | Result |
|---|---|---|---|
| . | String concatenate | 'Teddy' . 'Bear' | TeddyBear |
| = | Assignment | $a = 'Teddy' | $a variable contains 'Teddy' |
| + | Addition | 3+2 | 5 |
| - | Subtraction | 3-2 | 1 |
| - | Negation | -2 | -2 |
| ! | Not | !1 | 0 |
| * | Multiplication | 3*2 | 6 |
| / | Division | 3/2 | 1.5 |
| % | Modulus | 3%2 | 1 |
| ** | Exponentiation | 3**2 | 9 |
| <FILEHANDLE> | File input | <STDIN> | Read a line of input from standard input |
| >> | Right bit shift | 3>>2 | 0 (binary 11>>2=00) |
| << | Left bit shift | 3<<2 | 12 (binary 11<<2=1100) |
| | | Bitwise OR | 3|2 | 3 (binary 11|10=11 |
| & | Bitwise AND | 3&2 | 2 (binary 11&10=10 |
| ^ | Bitwise XOR | 3^2 | 1 (binary 11^10=01 |
2+3*4; # evaluates to 14, multiplication has precedence over addition (2+3)*4; # evaluates to 20, parentheses force the precedence |
These operators compare strings or numbers, returning TRUE or FALSE:
| Numeric Comparison | String Comparison | ||
|---|---|---|---|
| 3 == 2 | equal to | 'Teddy' eq 'Bear' | equal to |
| 3 != 2 | not equal to | 'Teddy' ne 'Bear' | not equal to |
| 3 < 2 | less than | 'Teddy' lt 'Bear' | less than |
| 3 > 2 | greater than | 'Teddy' gt 'Bear' | greater than |
| 3 <= 2 | less or equal | 'Teddy' le 'Bear' | less than or equal |
| 3 >= 2 | greater than or equal | 'Teddy' ge 'Bear' | greater than or equal |
| 3 <=> 2 | compare | 'Teddy' cmp 'Bear' | compare |
|   | 'Teddy' =~ /Bear/ | pattern match | |
The <=> and cmp operators return:
Perl has special file operators that can be used to query the file system. These operators generally return TRUE or FALSE.
Example:
print "Is a directory!\n" if -d '/usr/home'; print "File exists!\n" if -e '/usr/home/lstein/test.txt'; print "File is plain text!\n" if -T '/usr/home/lstein/test.txt'; |
There are many of these operators. Here are some of the most useful ones:
| -e filename | file exists |
|---|---|
| -r filename | file is readable |
| -w filename | file is writable |
| -x filename | file is executable |
| -z filename | file has zero size |
| -s filename | file has nonzero size (returns size) |
| -d filename | file is a directory |
| -T filename | file is a text file |
| -B filename | file is a binary file |
| -M filename | age of file in days since script launched |
| -A filename | same for access time |
|
| Contents |
Next |