Operators
## Learning Objectives
- Master arithmetic operators
- Understand string operators
- Learn comparison operators
- Work with logical operators
- Understand bitwise and file operators
## Arithmetic Operators
### Basic Operations
```perl
use strict;
use warnings;
my $a = 10;
my $b = 3;
print $a + $b; # 13 (addition)
print $a - $b; # 7 (subtraction)
print $a * $b; # 30 (multiplication)
print $a / $b; # 3.333... (division)
print $a % $b; # 1 (modulus)
print $a ** $b; # 1000 (10^3, exponentiation)
```
### Division Behavior
```perl
# Division always produces floating point
print 10 / 3; # 3.33333333333333
# Integer division
print int(10 / 3); # 3 (truncates)
print POSIX::floor(10 / 3); # 3 (floor)
```
### Increment/Decrement
```perl
my $x = 5;
# Pre-increment
print ++$x; # 6 (increments first, returns 6)
# Post-increment
print $x++; # 6 (returns 6, then increments)
print $x; # 7
my $y = 5;
print --$y; # 4
print $y--; # 4
print $y; # 3
```
## String Operators
### Concatenation
```perl
my $first = "Hello";
my $last = "World";
my $greeting = $first . " " . $last; # "Hello World"
# Concatenation assignment
my $str = "Hello";
$str .= " World"; # "Hello World"
```
### Repetition
```perl
my $dash = "-" x 40; # 40 dashes
my $pattern = "AB" x 3; # "ABABAB"
# Useful for formatting
print "+" . ("-" x 10) . "+\n";
# +----------+
```
## Comparison Operators
### Numeric Comparison
```perl
my $a = 10;
my $b = 20;
print $a == $b; # false (0)
print $a != $b; # true (1)
print $a < $b; # true (1)
print $a > $b; # false (0)
print $a <= $b; # true (1)
print $a >= $b; # false (0)
print $a <=> $b; # -1 (spaceship: -1, 0, or 1)
```
### String Comparison
```perl
my $a = "apple";
my $b = "banana";
print $a eq $b; # false ( "")
print $a ne $b; # true ("banana" ne "apple")
print $a lt $b; # true ("apple" lt "banana")
print $a gt $b; # false
print $a le $b; # true
print $a ge $b; # false
print $a cmp $b; # -1 (cmp returns -1, 0, or 1)
```
### Comparison Table
| Numeric | String | Meaning |
|---------|--------|---------|
| `==` | `eq` | Equal |
| `!=` | `ne` | Not equal |
| `<` | `lt` | Less than |
| `>` | `gt` | Greater than |
| `<=` | `le` | Less or equal |
| `>=` | `ge` | Greater or equal |
| `<=>` | `cmp` | Spaceship/compare |
## Logical Operators
### Basic Logic
```perl
my $true = 1;
my $false = 0;
print $true && $false; # false (0) - AND
print $true || $false; # true (1) - OR
print !$true; # false (0) - NOT
```
### Alternative Syntax
```perl
print $true and $false; # && and || have higher precedence
print $true or $false; # than 'and' and 'or'
# Use parens to be safe
print ($true and $false);
```
### Short-Circuit Evaluation
```perl
my $x = 0;
# Won't evaluate second part if first is false
if ($x != 0 && 10 / $x > 1) {
print "Condition met\n";
}
# Won't call function if first is true
if (defined $value || get_value()) {
# Use cached value or fetch new
}
```
## Bitwise Operators
### Binary Operations
```perl
my $a = 5; # 0101 in binary
my $b = 3; # 0011 in binary
print $a & $b; # 1 (0001 - AND)
print $a | $b; # 7 (0111 - OR)
print $a ^ $b; # 6 (0110 - XOR)
print ~$a; # -6 (compliment)
print $a << 1; # 10 (0101 << = 1010 - left shift)
print $a >> 1; # 2 (0101 >> = 0010 - right shift)
```
### Bit Manipulation
```perl
my $flags = 0b1010; # 10 in decimal
# Check if bit is set
if ($flags & 0b1000) {
print "Bit 3 is set\n";
}
# Set a bit
$flags = $flags | 0b0001; # 1011
# Toggle a bit
$flags = $flags ^ 0b0100; # 1111
```
## Assignment Operators
### Compound Assignment
```perl
my $x = 10;
$x += 5; # $x = 15
$x -= 3; # $x = 12
$x *= 2; # $x = 24
$x /= 4; # $x = 6
$x %= 5; # $x = 1
$x **= 2; # $x = 1
$x .= " hello"; # $x = "1 hello"
# String-specific
$x x= 3; # Repeat "1 hello" 3 times
```
## Range and Flip-Flop
### Range Operator
```perl
# Array context - creates list
my @nums = (1 .. 10); # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
# String range (character sequences)
my @letters = ('a' .. 'z');
my @ALPHA = ('A' .. 'Z');
# Scalar context - flip-flop
if (5 .. 10) { # True when condition in 5-10 range
print "In range\n";
}
```
## File Test Operators
### File Tests
```perl
use strict;
use warnings;
use -e File::Spec; # For cross-platform
my $file = "test.txt";
# Basic file tests
-e $file; # Exists?
-r $file; # Readable?
-w $file; # Writable?
-x $file; # Executable?
-f $file; # Regular file?
-d $file; # Directory?
-l $file; # Symbolic link?
-s $file; # Size in bytes (returns size or false)
# Combined
if (-e $file && -w $file) {
print "File exists and is writable\n";
}
```
### File Size
```perl
my $size = -s $file // 0;
print "Size: $size bytes\n";
if (-s $file > 1024 * 1024) {
print "File is larger than 1MB\n";
}
```
## Conditional Operator
### Ternary Operator
```perl
my $age = 25;
my $status = $age >= 18 ? "adult" : "minor";
print $status; # "adult"
# Can be nested
my $grade = $score >= 90 ? "A" :
$score >= 80 ? "B" :
$score >= 70 ? "C" : "F";
```
## Operator Precedence
### Highest to Lowest
| Priority | Operators |
|----------|---------------------------|
| 1 | `()` (grouping) |
| 2 | `++`, `--` (auto increment) |
| 3 | `**` (exponentiation) |
| 4 | `!`, `~`, `+`, `-` (logical not, bitwise not, unary) |
| 5 | `=~`, `!~` (pattern binding) |
| 6 | `*`, `/`, `%`, `x` |
| 7 | `+`, `-`, `.` |
| 8 | `<<`, `>>` (shift) |
| 9 | `-e`, `-r`, etc. (file tests) |
| 10 | `<`, `>`, `<=`, `>=` |
| 11 | `==`, `!=`, `eq`, `ne`, `<=>`, `cmp` |
| 12 | `&` (bitwise AND) |
| 13 | `\|`, `^` (bitwise OR, XOR) |
| 14 | `&&` |
| 15 | `\|\|` |
| 16 | `..` (range) |
| 17 | `?:` (ternary) |
| 18 | `=`, `+=`, `-=`, etc. |
| 19 | `,`, `=>` |
| 20 | `and` |
| 21 | `or`, `not` |
### Use Parentheses
```perl
# Clear and safe
if (($a + $b) * $c) { }
# Same but relying on precedence
if ($a + $b * $c) { } # $b * $c first, then + $a
```
## Summary
- Arithmetic: `+`, `-`, `*`, `/`, `%`, `**`
- Increment: `++$x`, `$x++`, `--$x`, `$x--`
- String: `.` (concatenation), `x` (repetition)
- Numeric comparison: `==`, `!=`, `<`, `>`, `<=`, `>=`, `<=>`
- String comparison: `eq`, `ne`, `lt`, `gt`, `le`, `ge`, `cmp`
- Logical: `&&`, `||`, `!`, `and`, `or`, `not`
- Bitwise: `&`, `|`, `^`, `~`, `<<`, `>>`
- File tests: `-e`, `-r`, `-w`, `-x`, `-f`, `-d`, `-s`
- Ternary: `condition ? true : false`
- Use parentheses to ensure correct precedence
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →