Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Operators

PetaPerl implements the full set of Perl 5 operators with identical semantics. All operators maintain Perl’s context sensitivity and precedence rules.

Binary Operators

Arithmetic

OperatorOperationExample
+Addition$a + $b
-Subtraction$a - $b
*Multiplication$a * $b
/Division$a / $b
%Modulus$a % $b
**Exponentiation$a ** $b

All arithmetic operators coerce operands to numeric context. Division by zero produces a warning and returns infinity or NaN.

my $x = 5 + 3;        # 8
my $y = 10 / 3;       # 3.333...
my $z = 2 ** 10;      # 1024
my $m = 17 % 5;       # 2

String

OperatorOperationExample
.Concatenation$a . $b
xRepetition$str x $count

String operators coerce operands to string context.

my $str = "Hello" . " " . "World";  # "Hello World"
my $rep = "X" x 5;                   # "XXXXX"
my $pad = " " x 10;                  # 10 spaces

Numeric Comparison

OperatorOperationReturns
==EqualTrue if equal
!=Not equalTrue if not equal
<Less thanTrue if less
>Greater thanTrue if greater
<=Less or equalTrue if ≤
>=Greater or equalTrue if ≥
<=>Three-way compare-1, 0, or 1

Numeric comparisons coerce operands to numbers.

if ($age >= 18) { ... }
my $cmp = $a <=> $b;  # -1 if $a < $b, 0 if equal, 1 if $a > $b

String Comparison

OperatorOperationReturns
eqEqualTrue if equal
neNot equalTrue if not equal
ltLess thanTrue if less
gtGreater thanTrue if greater
leLess or equalTrue if ≤
geGreater or equalTrue if ≥
cmpThree-way compare-1, 0, or 1

String comparisons use lexicographic (dictionary) ordering.

if ($name eq "John") { ... }
my $cmp = $a cmp $b;  # -1, 0, or 1

Logical

OperatorOperationShort-circuitsPrecedence
&&AndYesHigh
``Or
//Defined-orYesHigh
andAndYesLow
orOrYesLow
xorExclusive orNoLow

Logical operators return the last evaluated value, not just true/false.

my $result = $x && $y;         # Returns $y if $x true, else $x
my $default = $user || "guest"; # Returns "guest" if $user false
my $value = $config // 0;      # Returns 0 only if $config undefined

Defined-or (//): Unlike ||, this only checks if the left side is defined, not just true. 0 and "" are both false but defined.

my $x = 0;
my $a = $x || 10;   # 10 (0 is false)
my $b = $x // 10;   # 0 (0 is defined)

Bitwise

OperatorOperationExample
&Bitwise AND$a & $b
``Bitwise OR
^Bitwise XOR$a ^ $b
<<Left shift$a << $n
>>Right shift$a >> $n

Bitwise operators work on integers. Operands are converted to unsigned integers.

my $mask = 0xFF & $value;
my $flags = $READ | $WRITE;
my $double = $x << 1;

Range

OperatorOperationContext
..Inclusive rangeList context creates list
...Flip-flopScalar context is stateful
my @digits = (0..9);              # (0, 1, 2, ..., 9)
my @letters = ('a'..'z');         # ('a', 'b', ..., 'z')
for my $i (1..100) { ... }       # Loop 1 to 100

In scalar context, .. and ... are flip-flop operators (stateful boolean range).

Binding

OperatorOperationExample
=~Match$str =~ /pattern/
!~Not match$str !~ /pattern/

Binding operators connect strings with regex operations.

if ($email =~ /\@/) { ... }       # Contains @
if ($name !~ /^\d/) { ... }       # Doesn't start with digit

Unary Operators

Arithmetic

OperatorOperationExample
-Negation-$x
+Unary plus+$x
my $neg = -5;
my $pos = +$x;  # Numeric context

Logical

OperatorOperationExample
!Not!$x
notNot (low precedence)not $x
if (!$error) { ... }
die "Failed" if not $ok;

Bitwise

OperatorOperationExample
~Bitwise complement~$x
my $inverted = ~$bits;

Reference

OperatorOperationExample
\Create reference\$x, \@arr, \%hash
my $scalar_ref = \$value;
my $array_ref = \@data;
my $hash_ref = \%config;

Increment/Decrement

OperatorOperationWhen evaluated
++$xPre-incrementAfter increment
--$xPre-decrementAfter decrement
$x++Post-incrementBefore increment
$x--Post-decrementBefore decrement
my $x = 5;
my $a = ++$x;  # $x is 6, $a is 6
my $b = $x++;  # $x is 7, $b is 6

String increment: ++ on strings performs “magic increment” (Perl-style).

my $s = "aa";
$s++;  # "ab"
$s++;  # "ac"

File Test Operators

File test operators check properties of files and filehandles. All return true/false except -s which returns file size.

OperatorTestReturns
-eExistsBoolean
-rReadableBoolean
-wWritableBoolean
-xExecutableBoolean
-oOwned by effective UIDBoolean
-RReadable by real UIDBoolean
-WWritable by real UIDBoolean
-XExecutable by real UIDBoolean
-OOwned by real UIDBoolean
-zZero sizeBoolean
-sNon-zero sizeSize in bytes or false
-fRegular fileBoolean
-dDirectoryBoolean
-lSymbolic linkBoolean
-pNamed pipe (FIFO)Boolean
-SSocketBoolean
-bBlock special fileBoolean
-cCharacter special fileBoolean
-tTTY (terminal)Boolean
-uSetuid bit setBoolean
-gSetgid bit setBoolean
-kSticky bit setBoolean
-TText fileBoolean
-BBinary fileBoolean
-MModification time (days)Number
-AAccess time (days)Number
-CInode change time (days)Number
if (-e $file) { ... }               # File exists
if (-f $path && -r $path) { ... }   # Regular file and readable
my $size = -s $file;                # Size in bytes
if (-d $path) { ... }               # Is directory

Stacked file tests: -f -w -r $file checks all three conditions.

Other Unary Operators

OperatorOperationExample
definedCheck if defineddefined $x
if (defined $value) { ... }

Assignment Operators

Simple Assignment

OperatorOperationExample
=Assignment$x = 5
my $x = 10;
my ($a, $b, $c) = (1, 2, 3);  # List assignment

Compound Assignment

All binary operators have compound assignment forms:

OperatorEquivalentExample
+=$x = $x + $y$x += 5
-=$x = $x - $y$x -= 3
*=$x = $x * $y$x *= 2
/=$x = $x / $y$x /= 10
%=$x = $x % $y$x %= 7
**=$x = $x ** $y$x **= 2
.=$x = $x . $y$str .= "more"
x=$x = $x x $y$str x= 3
&=$x = $x & $y$bits &= $mask
`=``$x = $x
^=$x = $x ^ $y$x ^= $y
<<=$x = $x << $y$x <<= 2
>>=$x = $x >> $y$x >>= 1
&&=$x = $x && $y$x &&= $default
`=`
//=$x = $x // $y$x //= 0
my $count = 10;
$count += 5;        # 15
$count *= 2;        # 30

my $path = "/home";
$path .= "/user";   # "/home/user"

$cache ||= load_data();   # Only load if $cache is false
$config //= {};           # Only assign if $config is undef

Ternary Operator

OperatorSyntaxExample
? :Conditional$cond ? $then : $else
my $result = $x > 0 ? "positive" : "non-positive";
my $max = $a > $b ? $a : $b;

Ternary as lvalue: The ternary operator can be used as an assignment target.

($x > 0 ? $pos : $neg) = 10;  # Assigns to $pos or $neg

Array/Hash Subscripts

SyntaxOperationExample
$arr[index]Array element access$arr[0]
$hash{key}Hash element access$hash{name}
@arr[indices]Array slice@arr[1, 3, 5]
@hash{keys}Hash slice@hash{qw(a b c)}
my $first = $arr[0];
my $value = $hash{key};
my @subset = @arr[0, 2, 4];       # Elements 0, 2, 4
my @values = @hash{'a', 'b'};     # Values for keys 'a', 'b'

Arrow Operator

SyntaxOperationExample
->[]Array deref subscript$aref->[0]
->{}Hash deref subscript$href->{key}
->()Method call$obj->method()
my $element = $array_ref->[5];
my $value = $hash_ref->{name};
my $result = $object->method(@args);

Comma Operators

OperatorOperationUse
,List separator(1, 2, 3)
=>Fat commakey => value

The fat comma (=>) autoquotes barewords on its left side.

my %hash = (
    name => "John",     # 'name' autoquoted
    age => 30,
);

Operator Precedence

Highest to lowest precedence (same as Perl 5):

  1. Terms and list operators (left)
  2. -> (left)
  3. ++ -- (none)
  4. ** (right)
  5. ! ~ \ unary + unary - (right)
  6. =~ !~ (left)
  7. * / % x (left)
  8. + - . (left)
  9. << >> (left)
  10. Named unary operators
  11. < > <= >= lt gt le ge (none)
  12. == != <=> eq ne cmp ~~ (none) — ~~ smart match is partial
  13. & (left)
  14. | ^ (left)
  15. && (left)
  16. || // (left)
  17. .. ... (none)
  18. ?: (right)
  19. = += -= etc. (right)
  20. , => (left)
  21. List operators (right)
  22. not (right)
  23. and (left)
  24. or xor (left)

Use parentheses when precedence is unclear.

PetaPerl-Specific Notes

Parallelization

Operators execute sequentially by default. PetaPerl’s parallelization applies at the loop/map/grep level, not individual operators.

Performance

  • Bitwise operations compile to native machine instructions
  • String concatenation may allocate new memory (use .= for efficiency)
  • Numeric operations are optimized for integers and floats separately