Perl Operators

Perl Operator

Perl has a whole array of very useful operators. They can generally be classified as follows:


Comparison Operators:

You have to use different operator for numeric and string to accomplish the same task. String operators cannot be used for numeric values and vice versa.

Comparison Operators

String Numeric Purpose Syntax
eq == equal to true if $a == $b
true if $s1 eq s2
ne !- not equal to true if $a != $b
true if $s1 ne s2
lt < less than true if $a < $b
true if $s1 lt s2
gt > greater than true if $a > $b
true if $s1 gt s2
le <= less than or equal to true if $a <= $b
true if $s1 le s2
ge >= greater than or equal to true if $a >= $b
true if $s1 ge s2
cmp <=> comparison with a signed result 0 if equal
1 if $a greater
-1 if $b greater


String Operators:

Perl has a rich collection of string operators:

Operator
Purpose
. Concatenate


Numeric Operators:

Operator
Purpose

+

Addition

-

Substraction

*

Multiplication

/

Division

**

Raise the right operand to the power of the left operand

%

Modulo


Assignment Operators and Equivalence Operators:

These operators are already defined in the tables above in the context of numeric and string. For example = is an assignment operator and eq is an equivalence operator.

Operators

Name
Example
Comments
Arithmetic Operators
Addition
$a + $b
 
Multiplication
$a * $b
 
Modulus
$a % $b
 

Exponentiation
$a ** $b
 
String Operators
Dot operator
$a . $b
123 . 456 = 123456
x operator
$a x $b
123 x 3 = 123123123
increment
++$a, $a++
 
decrement
--$a, $a--
 
Logical Operators

And
$a && $b

also $a and $b
Or
$a || $b

also $a or $b
Not
! $a

also not $a

Named Operators

int

int(5.6234) 5
length length("nose") 4
lc

lc(LOWER)

lower
uc uc(upper) UPPER
cos cos(30) 0.8660
rand rand(5)

Returns a random number from 0 to less than its argument. If the
argument is omitted, a number between 0 to 1 is returned.

Operators


 

Operator precedence and associativity
Operators
Associativity
Terms and list operators (leftward) Left
-> Left
++   -- Nonassociative
** Right
! ~ \ and unary + and - Right
=~   !~ Left
* / % x Left
+ - .  Left
<<  >> Left
Named unary operators Nonassociative
<   >   <=   >=   lt  
gt   le   ge
Nonassociative
==  !=  <=>   eq   ne  
cmp
Nonassociative
& Left
|  ^ Left
&& Left
|| Left
.. Nonassociative
?: Right
=   ++   -+   *=   and  
so on
Right
,   => Left
List operators (rightward) Nonassociative
not Right
and Left
or xor Left

Autoincrement and Autodecrement

print ++($foo = '99');     # prints '100'

print ++($foo = 'a0');     # prints 'a1'


print ++($foo = 'Az');     # prints 'Ba'

print ++($foo = 'zz');     # prints 'aaa'

Exponentiation

-2**4 is -(2**4), not (-2)**4

Unary Operators

Unary ! performs logical negation which is "not"
Unary - performs arithmetic negation if the operand is numeric. If the operand is an identifier, a string consisting of a minus sign conccatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned.

Unary ~ performs bitwise negation, that is 1's complement.

Unary + has no semantic effect whatsoever, even on strings. It is syntactically useful for separating a function name from a parenthesized expression which would otherwise be interpreted as the complete list of function arguments.

Unary \ creates a reference to whatsoever follows.

Binding Operators

Binary =~ binds a scalar expression to a pattern match, substitution, or translation. These operations search or modify the string $- by default.

Binary !~ is just like =~ except the return value is negated in the logical sense. The following expressions are functionally equivalent:

$string !~ /pattern/
not $string =~ /pattern/

Multiplicative Operators

* / and % work as expected. If you have a floating point use fmod() instead of % because % converts its operands to integers before finding the remainder according to integer division.

Binary x is the repetition operator.

as a string replicator
print '-' x 80;                 
# print row of dashes
print "\t" x ($tab/8), ' ' x ($tab%);    # tab over
as a list replicator
@ones = (1) x 80;                 
# a list of 80 1's
@ones = (5)                  
# set all elements to 5
to initialize array and hash slices
@keys = qw(perls before swine);
@hash{@keys} = ("") x keys;
which is equivalent to
$hash{perls} = '"';
$hash{before} = "";
$hash{swine} = "";

Additive Operators

+ and - convert their arguments from strings to numeric values if necessary and return a numeric result. The "." operator provides string concatenation.

$almost = "Fred" . "Flintshone";           
# returns FredFlintstone
another method of concatenation is
$fullname = "$firstname $lastname";

Shift Operators

The bit-shift operators (<< and >>)

1 << 4;     # returns 16
32 >> 4;       # returns 4

Named Unary and File Test Operators

Some of the functions described in chapter 3 are really unary operators.

sleep 4 | 3  is  equivalent to (sleep 4) | 3
but
print 4 | 3 is equivalent to print (4 | 3)

This is so because sleep is a unary operator and list operator. When in doubt use parenthesis. Remember, if it looks like a function then it is a function.

A file test operator is a unary operator that takes one argument, either a filename or a filehandle, and tests the associated file to see if something is  true about it.

File Test Operators
Operator
Meaning
-r

File is readable by effective uid/gid
-w
File is writable by effective uid/gid
-x
File is executable by effective uid/gid
-o
File is owned by effective uid
 
-R
File is readabe by real uid/gid
-W
File is writable by real uid/gid
-X
File is executable by real uid/gid
-O
File is owned by real uid
 
-e
File exists 
-z
File has zero size
-s
File has non-zero size (returns size)
 
-f
File is a plain file
-d
File is a directory
-l
File is a symbolic link
-p
File is a named pipe (FIFO)
-S
File is a socket

-b
File is a block special file
-c
File is a character special file
-t
Filehandle is opened to a tty
 

-u
File has setuid bit set
-g
File has setgid bit set
-k
File has sticky bit set
 

-T
File is a text file
-B
File is a binary file (opposite of -T)
 
-M
Age of file (at startup) in days since modification

-A
Age of file (at startup) in days since last access
-C
Age of file (at startup) in days since inode change

Bitwise Operators

Bitwise AND, OR, and XOR: &, |, and ^. Both operands must be of
the same type.

case
code
result
string AND string
"123.45" & "234.56"
020.44 (Remember, it is bitwise AND)

string AND numeric
"123.45" & 234.56

106
numeric AND numeric
123.45 & 234.56
106
integer AND integer
123 & 234

106

C-style Logical (Short Circuit) Operators


And: $a && $b       # $a if $a
is false, $b otherwise

Or:   $a || $b           

# $a if $a is true, $b otherwise

open(File, "filename") || die "Cannot open somefile: $!\n";

Range Operator

The range operator .. performs two different tasks. In a list context,
it returns a list of values counting (by ones) from the left value to the
right value.

for (101 .. 200)  { print; }     # prints
101......200

@foo = @foo[0 .. $#foo];     # an expensive no-op

@foo = @foo[ -5 .. -1];     # slice last 5 items

@alphabet = ('A' .. 'Z');     # prints ABCDEFGHIJKLMOPQRSTUVWXYZ

In scalar context, .. returns a Boolean value.

if (101 .. 200) { print; }     # print 2nd hundred
lines

next line if (1 .. /^$/);     # skip header lines

s?^/> / if (/^$/ .. eof());     # quote body

Angle Operator

The angle operator (<>),
sometimes called a diamond operator, is primarily used for reading and writing
files.

viagra without prescription