Perl operators are essential symbols or keywords that perform operations on variables and values. They are fundamental to writing efficient and powerful Perl code.
Arithmetic operators perform mathematical calculations. Perl supports standard arithmetic operations:
+
(addition)-
(subtraction)*
(multiplication)/
(division)%
(modulus)**
(exponentiation)These operators compare values and return true or false. Perl has separate operators for numeric and string comparisons:
Numeric | String | Description |
---|---|---|
== |
eq |
Equal to |
!= |
ne |
Not equal to |
< |
lt |
Less than |
> |
gt |
Greater than |
<= |
le |
Less than or equal to |
>= |
ge |
Greater than or equal to |
Logical operators combine conditional statements:
&&
(and)||
(or)!
(not)These operators assign values to variables. The basic assignment operator is =
, but Perl also supports compound assignment operators:
+=
-=
*=
/=
%=
Perl provides operators specifically for string manipulation:
.
(concatenation)x
(string repetition)
my $x = 10;
my $y = 3;
print $x + $y; # Output: 13
print $x - $y; # Output: 7
print $x * $y; # Output: 30
print $x / $y; # Output: 3.33333333333333
print $x % $y; # Output: 1
print $x ** $y; # Output: 1000
$x += 5; # $x is now 15
print $x; # Output: 15
my $a = 5;
my $b = "5";
if ($a == $b && $a eq $b) {
print "Equal numerically and as strings\n";
} elsif ($a == $b || $a eq $b) {
print "Equal either numerically or as strings\n";
} else {
print "Not equal\n";
}
# Output: Equal either numerically or as strings
eq
, ne
, etc.) when comparing strings to avoid unexpected type coercion.Understanding Perl operators is crucial for effective programming. They form the backbone of Perl Control Structures and are essential in Perl Data Manipulation. As you progress, explore more advanced concepts like Perl Bitwise Operators and Perl File Test Operators to enhance your Perl programming skills.