Perl Programming/Operators

= Introduction =

Perl's set of operators borrows extensively from the C programming language. Perl expands on this by infusing new operators for string functions (.=, x, eq, ne, etc.). C by contrast delegates its subset of Perl functionality to a library strings.h, and ctype.h, and includes no such functionality by default compilation. Perl also includes a highly flexible Regex engine inspired by Sed with improvements to standard POSIX regexes, most notably the support of Unicode.

= The operators =

Arithmetic
Most arithmetic operators are binary operators; this means they take two arguments. Unary operators only take one argument. Arithmetic operators are very simple and often transparent.

Binary
All the basic arithmetic operators, addition (+), subtraction (-), multiplication (*), and division (/), and the modulus operator <tt>%</tt> exist. Modulus returns the remainder of a division (<tt>/</tt>) operation.

The exponentiation operator is <tt>**</tt>. It allows you to raise one value to the power of another. If you raise to a fraction you will get the root of the number. In this example the second result when raised to the power of 2 should return 2 (<tt>(2**(1/2))**2 = 2</tt>).

The function <tt>sqrt</tt> is provided for finding a square root. Other fractional powers (i.e., (1/5), (2/13), (7/5), and similar) are suitably found using the <tt>**</tt> operator.

Unary
The auto-decrement (<tt>--</tt>), and auto-increment (<tt>++</tt>) operators are unary operators. They alter the scalar variable they operate on by one logical unit. On numbers, they add or subtract one. On letters and strings, only the auto-increment shift one up in the alphabet, with the added ability to roll-over. Operators that come in post- and pre- varieties can be used two ways. The first way returns the value of the variable before it was altered, and the second way returns the value of the variable after it was altered.

Assignment
The basic assignment operator is <tt>=</tt> that sets the value on the left side to be equal to the value on the right side. It also returns the value. Thus you can do things like <tt>$a = 5 + ($b = 6)</tt>, which will set <tt>$b</tt> to a value of 6 and <tt>$a</tt> to a value of 11 (5 + 6). Why you would want to do this is another question.

The assignment update operators from C, <tt>+=</tt>, <tt>-=</tt>, etc. work in perl. Perl expands on this basic idea to encompass most of the binary operators in perl.

Comparison
Perl uses different operators to compare numbers and strings. This is done, because in most cases, Perl will happily stringify numbers and numify strings. In most cases this helps, and is consistent with Perl's DWIM Do-What-I-Mean theme. Unfortunately, one place this often does not help, is comparison.

Logical
Perl has two sets of logical operators, just like the comparison operators, however not for the same reason.

The first set (sometimes referred to as the C-style logical operators, because they are borrowed from C) is <tt>&amp;&amp;</tt>, <tt>||</tt>, and <tt>!</tt>. They mean logical AND, OR, and NOT respectively. The second set is <tt>and</tt>, <tt>or</tt>, and <tt>not</tt>.

The only difference between these two sets is the precedence they take (See Precedence). The symbolic operators take a much higher precedence than the textual.

Conditionals
Most of the time, you will be using logical operators in conditionals.

In this case, you could safely substitute <tt>and</tt> for <tt>&&</tt> and the conditional would still work as expected. However, this is not always the case.

This, however, is completely different.

Most people prefer to use C-style logical operators and use brackets to enforce clarity rather than using a combination of textual and C-style operators (when possible), which can be very confusing at times.

Partial evaluation
Partial evaluation (or "short circuiting") is the property of logical operators that the second expression is only evaluated, if it needs to be.

This also works with logical OR statements. If the first expression evaluates as true, the second is never evaluated, because the conditional is automatically true.

This becomes useful in a case like this:

Here, if the <tt>foo</tt> subroutine returns false, "foo failed\n" is printed. However, if it returns true, "foo failed\n" is not printed, because the second expression (<tt>print "foo failed\n"</tt>) does not need to be evaluated.

Bitwise
These operators perform the same operation as the logical operators, but instead of being performed on the true/false value of the entire expressions, it is done on the individual respective bits of their values.


 * <tt>&</tt> (bitwise AND)
 * <tt>|</tt> (bitwise OR)
 * <tt>^</tt> (bitwise XOR)
 * <tt>~</tt> (bitwise NOT)

The left and right shift operators move the bits of the left operand (e.g. $a in the case of $a << $b) left or right a number of times equal to the right operand ($b). Each move to the right or left effectively halves or doubles the number, except where bits are shifted off the left or right sides. For example, $number << 3 returns $number multiplied by 8 (2**3).


 * <tt><<</tt> (left shift)
 * <tt>>></tt> (right shift)

String
The string concatenation operator is <tt>.</tt>, not <tt>+</tt> that some other languages use.

There is a repeat operator for strings (<tt>x</tt>) that repeats a string a given number of times.

Comparing strings
To compare strings, use <tt>eq</tt> and <tt>ne</tt> instead of <tt>==</tt> or <tt>!=</tt> respectively. You can also look for a substring with <tt>substr</tt>, or pattern-match with regular expressions.

File Test

 * See Perl Programming/Function Reference

Other
The range operator (..) returns a list of items in the range between two items; the items can be characters or numbers. The type of character is determined by the first operand; the code: print ('A'..'Z'); print ('a'..'z'); print ('A'..'z'); print (1..'a'); print (1..20); print ('&'..'!'); print (10..-10); print "$_\n" foreach (1..10); Outputs (Newlines added for readability): ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ

1234567891011121314151617181920 &

1 2 3 4 5 6 7 8 9 10 Note that the case is defined by the first operand, and that the <tt>1..'a'</tt> and <tt>(10..-10)</tt> operations return empty list.

Precedence
Precedence is a concept that will be familiar to anyone who has studied algebra or coded in C/C++. Each operator has its place in a hierarchy of operators, and are executed in order. The precedence of perl operators is strict and should be overridden with parentheses, both when you are knowingly going against precedence and when you aren't sure of the order of precedence. For a complete listing of the order, check perlop.

The smart match operator
The smart match operator <tt></tt> is new in perl 5.10. To use it, you'll need to explicitly say that you're writing code for perl 5.10 or newer. Its opposite operator <tt>ǃ~</tt> matches smartly an inequality:

The smart match operator is versatile and fast (often faster than the equivalent comparison without <tt>ǃ~</tt> or <tt></tt>). See smart matching in detail for the comparisons it can do. <tt></tt> is also used in the <tt>given/when</tt> switch statement new in 5.10, which will be covered elsewhere.

The doubledollar
A variable, previously referenced with the reference operator can be dereferenced by using a doubledollar symbol prefix:

The arrow operator
If the left hand operand of the arrow operator is an array or hash reference, or a subroutine that produces one, the arrow operator produces a look up of the element or hash:

Perl/演算子