\chapter{Operators\label{chap:op}}

\section{Introduction}

\term{Operators} are important elements in any programming language. They are so called because 
they operate on data. For those who are new to computer programming the operators with which they may be 
most familiar are the arithmetic operators, like addition, subtraction, multiplication and division. Yet 
there are many more varieties of operators in programming languages. Perl provides more operators than 
most programming languages I could think of, but most of them fall within one of the several categories 
that we would go into detail in this chapter. Although devoting an entire chapter to discuss operators
is rather boring, it is important for you to understand what operators are as they act as the glue to
bind pieces of data into an expression. \\

\term{Arithmetic operators} manipulate on numeric scalar data. Perl can evaluate an arithmetic 
expression, in a way similar to our daily-life mathematics. \\

\term{Assignment operators} are used to assign scalar or list data to a data structure. Apart 
from \mono{=} that you learned earlier, there are other operators, like \mono{+=}, that perform
additional operations at the same time. \\

\term{Comparison operators} are used to compare two pieces of scalar data, e.g. alphabetically 
or numerically and returns a Boolean value. For example, you have two variables and you can use a 
comparison operator to deduce which one is numerically larger. \\

\term{Equality operators} compares two pieces of scalar data and returns if their values are 
identical. They may be considered special cases of comparison operators. \\ 

\term{Bitwise operators} provide programmers with the capability of performing bitwise calculations. \\

\term{Logical operators} can be used to do some Boolean logic calculations. \\

\term{String manipulation operators} manipulate on strings. \\

There are some other operators that do not fall into the categories above. Some of them will be 
covered in this chapter, and the rest would be introduced as needed in subsequent chapters in this 
tutorial. \\

Because Perl classifies all data into one of the two forms, namely scalar and list data, operators 
can be classified, similarly according to the number of operands, into two groups. Either the number of
operands is fixed or variable. An operator that takes on one, two and three operands are referred to 
as \term{unary}, \term{binary} and \term{ternary} operators, respectively. \term{List operators},  
on the other hand, can take a list of arguments as operands. \\

\section{Description of some Operators}

In this section we shall study a number of operators. This is not intended to be a full coverage 
because it would be better for you to learn the rest later on in the tutorial as you accumulate more
Perl knowledge. If you would like to have a detailed reference of the whole family of operators in Perl, 
please consult the \link{http://www.perldoc.com/perl5.8.0/pod/perlop.html}{perlop} manpage. \\

\subsection{Arithmetic Operators}

Arithmetic operators refer to the following operators: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator}	& \textbf{Description}	\\
\hline 
\mono{+} &	Addition operator \\
\mono{-} & 	Subtraction operator \\
\mono{*} &	Multiplication operator \\
\mono{/} &	Division operator \\
\mono{\%} &	Modulus operator \\
\mono{+} 	&	Positive sign \\
\mono{-} 	&	Negative sign \\
\mono{++} &	Autoincrement operator \\
\mono{--} & 	Autodecrement operator \\
\mono{**} & 	Exponentiation operator \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

The operators \mono{+}, \mono{-}, \mono{*}, \mono{/} take two operands and return the sum, 
difference, product and quotient respectively. Note that the division operation is floating-point division. 
Unlike C, Perl does not offer builtin integral division. To get the integral quotient, you may use the 
\mono{int()} function. For example, \mono{int(7 / 2)} evaluates to $3$. \\

Perl won't round a number to the \textit{nearest} integer for you automatically. If you need this,
the ``correct'' way to do this is \\

\begin{verbatimtab}[4]
	$num = 7 / 2;
	print int($num+0.5), "\n";
\end{verbatimtab}

The modulus operator is more problematic. The operands of this operand are both integers. If you 
feed any floating-point numbers (i.e. decimals) as operands they will be coerced to integers. Assume 
we are carrying out \mono{\$a \% \$b}. \\

If \mono{\$b} is positive, the value returned is \mono{\$a} minus the largest integral multiple of 
\mono{\$b} such that the result is still positive. For example, \\

\mono{63 \% 5 = 3} ($63=12\times5+3$, the largest multiple in this case is $12$) \\

\mono{-63 \% 5 = 2} ($-63=-13\times5+2$, the largest multiple in this case is $-13$) \\

If \mono{\$b} is negative, the value returned is \mono{\$a} minus the largest integral multiple of 
\mono{\$b} such that the result is still negative. For example, \\

\mono{63 \% -5 = -2} ($63=(-13)\times(-5)+(-2)$, the largest multiple in this case is $-13$) \\

\mono{-63 \% -5 = -3} ($-63=12\times(-5)+(-3)$, the largest multiple in this case is $12$) \\

Such behaviours are so tedious that most programmers simply use the modulus operator for the first 
case --- where both operands are positive integers, which evaluates to the remainder of \mono{\$a / \$b}. \\

The positive/negative signs, just as in our usual mathematics, are unary operators that are affixed 
before a number to indicate whether it is positive or negative. Our usual convention is that the unary 
positive sign is not specified, because it is the default as expected. \\

If you know C/C++, the autoincrement and the autodecrement operators are identical to what you have 
learned. For those who don't know, it's worth to spend a few minutes to repeat all the details here. These 
operators can be placed before or after a variable. There are four possible variations: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Expression} & \textbf{Description} \\
\hline
\mono{++\$var} &	Prefix Increment \\
\mono{\$var++} &	Postfix Decrement \\
\mono{--\$var} &	Prefix Decrement \\
\mono{\$var--} &	Postfix Decrement \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

The first two are autoincrement, while the remaining two are autodecrement. If autoincrement/autodecrement 
is performed as a statement on its own, the prefix or postfix configurations do not produce any difference. 
For example, both \mono{++\$a;} and \mono{\$a++;} as standalone statements increase the value of 
\mono{\$a} by 1. However, they are different if the operators are used as part of a statement. Consider 
the following examples: \\

\renewcommand{\labelenumi}{\Alph{enumi}.}
\begin{enumerate}
\setlength{\itemsep}{-0.15cm}
\item \mono{\$b = ++\$a;} 
\item \mono{\$b = \$a++;} 
\end{enumerate}

In statement A, \mono{\$a} is first incremented, and then the new value is returned. In statement B, 
however, the value is returned first, and then \mono{\$a} is incremented. Therefore, the value returned 
(and is thus assigned to \mono{\$b}) is the value before increment. The two forms differ in the order 
of increment/decrement and return of value. Autodecrement works in the same way, except the variable is 
decremented instead. \\

In other words, statement A and statement B are identical in effect as the following respectively: \\

\begin{verbatimtab}[4]
	++$a; $b = $a;		# equivalent to statement A 
	$b = $a; ++$a;		# equivalent to statement B 
\end{verbatimtab}

The exponentiation operator calculates the n\super{th} power of a number. For example, $4^3$, i.e. \mono{4*4*4} 
is expressed by \mono{4**3}, and the result is $64$. Both operands can be floating point numbers. \\

All the operands discussed in this section take on scalar values only. In other words, they create a
scalar context for the operands. \\

\subsection{String Manipulation Operators}

String manipulation operators include the following: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator}	& \textbf{Description}	\\
\hline 
\mono{x} &	String repetition operator \\
\mono{.} &	String concatenation operator \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

The string concatenation operator is used to concatenate two strings. In other words, it glues two 
pieces of string together. For example, \\

\begin{verbatim}
"hello " . "guy"
\end{verbatim}

results in the string ``hello guy''. \\

You can concatenate as many pieces of string as you wish by using a series of concatenation operators 
together, like this: \\

\begin{verbatim}
$username . ", your disk quota is " . $quota . " Megabytes."
\end{verbatim}

In general, the concatenation operator dictates that both operands must be strings, and numeric 
operands would be converted to string form before concatenation (still remember that Perl does type
conversions internally if necessary?). However, Perl can become highly confused about whether you are 
using the concatenation operator or the decimal point if both operands are numeric literals. For example: \\

\begin{enumerate}
\setlength{\itemsep}{-0.15cm}
\item{\mono{print "1"."1";} (return: ``11'')}
\item{\mono{print "1".1;} (return: ``11'')}
\item{\mono{print 1."1";} (return: ``11'')}
\item{\mono{print 1.1;} (return: 1.1)}
\item{\mono{print 1 . 1;} (return: ``11'')}
\item{\mono{print 1. 1;} (return: error!)}
\item{\mono{print 1 .1;} (return: ``11'')}
\end{enumerate}

In case A, B and C, Perl thinks that the dot represents the concatenation operator because one or
more operands is a string literal. Note the difference between cases D and E. Although whitespace does 
not influence how Perl interprets an expression in general, this is not the case as shown in this example. 
In case D, because the dot follows the first 1 immediately, Perl thinks that you would like to use the 
decimal point, and returns the numeric value $1.1$. In case E, however, because there is a space before 
the dot, Perl thinks that you would like to use the string concatenation operator, and glues them up 
for you. So is case G. \\

However, in case F, Perl thinks that you would like to supply a floating-point number like in case D, 
but you supply it with two numbers with no comma in between (note that $1.$ is identical to $1$), so 
this is a syntax error! You get the same error if you replace case F with \mono{print 2 3;}. However, 
because it is nonsense (although allowed) to concatenate two literals, just take this as some 
extra information and little attention can be paid to it. \\

In scalar context, the string repetition operator returns the string specified by the left operand 
repeated the number of times specified by the right operand. For example, \\

\begin{verbatim}
$str = "ha" x 5;
\end{verbatim}

results in the string ``hahahahaha'' being assigned to \mono{\$str}. \\

In list context, if the left operand is a list in parentheses, it repeats the list the specified 
number of times. Examples: \\

\begin{verbatimtab}[4]
@array = ("a") x 3;		# or even (a) x 3 will work, but not a x 3
\end{verbatimtab}

results in the list \mono{("a", "a", "a")} being assigned to \mono{@array}. \\

\begin{verbatim}
@array = 3 x @array;
\end{verbatim}

% Question: what about $something = ('a', 'b') x 3; ?		# Ans: bbb (since list operator in effect)

replaces all the elements with the value 3. Note that the second operand always has a scalar numeric 
context. \\

\subsection{Comparison Operators}

In Perl, there are two sets of comparison operators. The first set compares the operands numerically: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator}	& \textbf{Description}	\\
\hline 
\mono{<} &	less than \\
\mono{>} &	greater than \\
\mono{<=} &	less than or equal to \\
\mono{>=} &	greater than or equal to \\
\mono{<=>} &	general comparison \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

The second set compares the operands stringwise: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator}	& \textbf{Description}	\\
\hline 
\mono{lt} &	less than \\
\mono{gt} &	greater than \\
\mono{le} &	less than or equal to \\
\mono{ge} &	greater than or equal to \\
\mono{cmp} &	general comparison \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

At this point it is important to tell you one behaviour of Perl. As you know, Perl differentiates only 
scalar and list data. That implies that Perl is quite ignorant about whether the value of a given variable 
(or a scalar element of a list) is a string or a number. This is why we have two sets of comparison operators 
defined in Perl, in this way the programmer should choose the appropriate set of comparison operator for
comparison. \\

% TODO: put somewhere else before this
Because of the fact that Perl does not differentiate string and numbers much, it allows you to use a 
string wherever a number is required, and vice versa. However, this involves a conversion that I have to 
explain it here. This behaviour is not specific to comparison operators only, but a general rule that you 
have to bear in mind at all times when you are writing your own scripts. Consider the two statements below: \\

\begin{enumerate}
\setlength{\itemsep}{-0.15cm}
\item{\mono{print "23.1abc" + 4;}}
\item{\mono{print "23.1abc" . 4;}}
\end{enumerate}

The addition operator (+) requires a numeric context (i.e. it requires numeric values as operands). 
Therefore, Perl extracts the leading numeric portion of the double-quoted string until a non-numeric 
character is encountered, and converts this portion into a number (which yields $23.1$ in this example). 
4 is then added to this number, thus yielding $27.1$ for the first statement. But what if the string 
started with non-numeric characters? Simply a 0 is returned. Also, if the string-to-number conversion 
involves a string that contains any non-numeric characters, Perl will display a warning message if you 
have warnings turned on. \\		% state advantage: something like 2cm can be extracted easily

The concatenation operator (.) requires a string context. Therefore, Perl converts the second operand 
(4) into a string and is then appended to the end of the first operand (``23.1abc''), thus yielding the 
output ``23.1abc4''. This is how Perl automatically converts between numbers and strings to and forth 
as needed. \\

Comparing two numbers is easy, but what about two strings? How does the computer compare two strings, 
possibly with non-alphanumeric characters in it? Perl compares two strings by comparing the \term{ASCII Code} 
of each individual character in the string. As internally the computer only recognizes numbers, a way of
representing characters with numbers have to be devised. ASCII representation is one of the several schemes
available, and is well adopted. You can go to \link{http://www.asciitable.com}{this website} to consult the 
ASCII Table, which contains the characters with their associated ASCII code. ASCII codes are in the range 
0 - 127, and there is an extended set in the range 128 - 255 which is not well supported on many systems. 
Don't ask me why the characters are assigned in this way. The ASCII table was defined as such, and there's 
little significance about its origin anyway. Let's compare the two pieces of string in this example: \\

``Urgent'', ``agent'' \\

Perl compares character by character. First compare the first character of the two strings, `U' and `a'. 
`U' has the ASCII code of 85, while `a' is 97. Because 97 is greater than 85, Perl decides that the latter 
character is greater, and thus ``agent'' is greater than ``Urgent''. In the case of comparing ``tooth'' 
and ``toothpicks'', the longer one prevails for obvious reasons. \\

After you have learned how Perl handles string and numeric comparison in general, it's time to look at 
how you specify the comparison with Perl. That's easy, because you merely put the appropriate operator in 
between the two operands. For example, to test if ``agent'' is less than ``Urgent'' stringwise, simply 
specify \mono{"Urgent" lt "agent"}, and the result is true. Note that Perl does not have the intrinsic 
Boolean type, so if you pass the result directly to the \mono{print} function, it is customary for Perl 
to output 1 for true, and ``'' (an empty string) for false. The best way to have the test result displayed 
properly is by using the conditional operator \mono{?:}. I will talk about this shortly later on in this 
chapter, but this is how you can do it: \\

\begin{verbatim}
print "Urgent" lt "agent" ? "true" : "false";
\end{verbatim}

causes the word ``true'' to be printed if the test is true, and ``false'' is printed if otherwise. \\

Here is another example showing how numeric comparison may be used to decide on which block of code
to be executed: \\

\begin{verbatimtab}[4]
if ($score >= 90) {
	print "Well done. Your score is $score.\n";		# A
} else {
	print "Work hard. Your score is $score.\n";		# B
}
\end{verbatimtab}

In the next chapter you will learn how to use the conditional statement like \mono{if} as presented in this
example. Basically, the concept is simple. If the value of \mono{\$score} is greater than or equals
90, statement A is printed; statement B is printed otherwise. \\

Be aware that you may get different results if you compare two pieces of scalar data numerically 
or stringwise! \\

% Unix (ba)sh shell scripting language has an opposite idiom that lt is for numeric comparison while
% < is for stringwise comparison. If you are on a Unix/Linux platform, please beware of this trap.

The \mono{<=>} and \mono{cmp} operators can be regarded as general comparison operators. Because of 
the shape, they are sometimes referred to in Perl manpages as \textit{spaceship operators}. \mono{<=>}
compares numerically while \mono{cmp} compares stringwise. The action of these two operators are similar,
and I shall take \mono{<=>} as an illustration. \\

The characteristics of \mono{<=>} is as follows. Denote the left operand as \mono{\$a} and the right
operand \mono{\$b}. If \mono{\$a < \$b}, the result is -1. If \mono{\$a > \$b}, the result is 1. If 
both operands are equal, that is, \mono{\$a == \$b} (see below), the result is 0. This is a handy
operator to quickly establish a trichotomy by determining in a single operation whether a number is
greater than, equal to or less than another. Despite its power, it is seldom used in practice.
It is mostly used with the \mono{sort()} function to sort a list of scalars in a convenient manner. \\

\subsection{Equality Operators}

Equality operators include the following: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator} & \textbf{Description} \\
\hline
\mono{==} &	equal (numeric comparison) \\
\mono{!=} &	not equal (numeric comparison) \\
\mono{eq} &	equal (stringwise comparison) \\
\mono{ne} &	not equal (stringwise comparison) \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

Similar to the case for comparison operators, we have two sets of equality operators. One set for 
numeric comparison, the other set for strings. Equality operators can usually be regarded as part of 
the comparison operators, but some books may prefer to classify them into two categories. There's 
actually little point to argue which approach is better, as different book authors take different views. 
Equality operators compares two pieces of scalar data and return a Boolean value (again, scalar value 
instead in Perl) that indicates if the two pieces of data are identical. \\

The first two operators compare numerically, while the remaining two compare stringwise. For the 
equal operators (\mono{==}, \mono{eq}) they return true if the two operands are identical, false 
if otherwise. The inequality operators (\mono{!=}, \mono{ne}) have an opposite sense, they return 
false if the two operands are identical, true if otherwise. \\

The equality and comparison operators we have covered so far are concluded by these four examples: \\

\begin{enumerate}
\setlength{\itemsep}{-0.15cm}
\item{\mono{'true' == 'false'  \# true !!}}
\item{\mono{'add' gt 'Add'     \# true}}
\item{\mono{'adder' gt 'add'   \# true}}
\item{\mono{'10' lt '9'        \# true}}
\end{enumerate}

In example A, \mono{==} requires a numeric context, thus both strings are converted into 0. Both 
sides are equal and evaluates to true (although you would receive a warning if \mono{\textbf{-w}} is enabled).
In example B, Perl will stop after checking the first character since `a' is greater than `A'. Beware that 
in the ASCII table capital characters have smaller ASCII codes than the small letter counterparts!
In example C, because the first three characters are the same and Perl cannot yet deduce whether 
`adder' is greater than `add' the longer string shall be considered greater.
In example D, since we compare with \mono{lt}, `1' is less than `9', therefore, the comparison 
evaluates to true. This example and example A illustrate why in Perl we need 2 sets of comparison operators. 
Because Perl is loosely typed and does type conversions automatically, there should be a method for Perl to 
know whether you would like to compare them as numbers or strings. \\

\subsection{Logical Operators}

Logical operators include the following: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator} & \textbf{Description} \\
\hline
\mono{|| or} & Logical OR \\
\mono{\&\& and} & Logical AND \\
\mono{! not} & Logical NOT, i.e. negation \\
\mono{xor} & Logical XOR --- Exclusive OR \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

The logical operators performs Boolean logic arithmetic. We have seen how to do a test using the comparison 
and equality operators. But what if you would like to carry out two or more tests and check if all of them are 
true? Boolean algebra can do it rather easily. However, it is out of the scope of this tutorial somehow for me 
to teach you the specifics of Boolean algebra, and I would focus on how to use the Perl logical operators only. \\

You may discover that there are two sets of \mono{OR}, \mono{AND} and \mono{NOT} operators. \mono{||},
\mono{\&\&} and \mono{!} refer to the C-Style version. If you know C/C++, these operators would look familiar 
to you, and are continued to be supported in Perl. Perl also has its own set, consisting of \mono{or}, 
\mono{and}, \mono{not} and \mono{xor}. Note that Perl gives you an extra \mono{xor} logical operator, 
that is not available in C/C++. The two sets differ only by precedence (which you will learn in the next section). 
The C-style operators have higher precedence, while the Perl operators have the lowest precedence among all the 
Perl operators. \\

In the above example, we would like to see if the results of both tests are true. We can then use either 
logical AND operator to do it. The result would be true only if both tests are true, and false if otherwise. 
The logical OR operators return false only when both tests are false, and true if otherwise. The logical NOT 
operator toggles the truth value. For example, \mono{!(13 < 25)} is false, because it inverts the truth value 
of \mono{13 < 25}, which is true. \\

The exclusive or operator returns true if exactly one of the two operands is false. That is, one is 
true while the other is false. \\

Here is the truth table of the logical operators we have covered so far: \\

\begin{table}[htbp]
\begin{center}
\begin{tabular}{cccccc}
\hline
\textbf{test1}	&	\textbf{test2}	& \mono{    } &	\textbf{\mono{ and  \&\& }}	&	\textbf{\mono{ or  || }}	&	\textbf{\mono{ xor }}	\\
\hline 
true			&	true			& 				&	true							&	true						&	false	\br \\
true			&	false			& 				&	false							&	true						&	true	\br	\\
false			&	true			& 				&	false							&	true						&	true	\br	\\
false			&	false			& 				&	false							&	false						&	false	\br \\
\hline
\end{tabular}

\addvspace{\baselineskip}

\begin{tabular}{cc}
\hline
\textbf{test}	&	\textbf{\mono{not  !}}	\\
\hline 
true			&	false			\br \\
false			&	true			\br	\\
\hline
\end{tabular}

\end{center}
\caption{Truth table of various Perl logical operators}\label{tab:logicalop}
\end{table}

Here are several examples to conclude: \\

\mono{(4<8) \&\& (16<32)} (return: true) \\
\mono{(4<8) xor (16<32)} (return: false) \\
\mono{(4<8) || (16<10)} (return: true) \\

Another important behaviour I haven't told you yet concerning logical operators is the short-circuiting 
property. Take \mono{and} as an example. Given the expression \\

\begin{verbatim}
(4 > 6) and (5 < 7)
\end{verbatim}

you can tell by merely looking at the first expression that the whole expression is false, regardless of 
the value of the second expression. Similar to the case for the \mono{or} operator, if the first operand 
evaluates to true already, it is not necessary for Perl to examine the second expression. Therefore, Perl 
will just ignore that expression and do NOT even attempt to evaluate it. This behaviour is known as short-
circuiting. The logical AND as well as logical OR operators support short-circuiting. \mono{xor}, for 
example, cannot short-circuit because its nature requires the value of both expressions be examined. \\

% TODO: do it or die

Short-circuiting is significant because it eliminates several runtime errors, in particular in the 
following example we will not get the ``division by zero'' error because of short-circuiting: \\

\head{EXAMPLE}{Safe Division}
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/eg0401.pl}

\addvspace{\baselineskip}

The core of the program is on line 12, which appears to be a little bit complicated. This example
makes use of short-circuiting property of \mono{\&\&} and \mono{||}. Let's consider two cases, when
\mono{\$y} is non-zero and zero. \\

Consider the case if \mono{\$y} is non-zero. First \mono{\$y} is evaluated. Because it is not zero, 
the short-circuiting property of \mono{||} causes the second operand \mono{undef} not to be evaluated.
Therefore, the first operand of \mono{\&\&} is \mono{\$y} itself. Because it is non-zero, the second
operand has to be evaluated, which calculates the quotient, which is assigned to \mono{\$quotient}. \\

If \mono{\$y} is zero, then the second operand of \mono{||} has to be evaluated, which is \mono{undef}. 
The operand of \mono{\&\&} is thus \mono{undef}. Because this value is interpreted as a false value in
Boolean context, the second operand of \mono{\&\&} is not evaluated and thus \mono{undef} is assigned
to \mono{\$quotient}. \\

Subsequently, a check of whether \mono{\$quotient} is \mono{undef} is sufficient to tell whether 
``division by zero'' occurs. Depending on this result, either an error message or the quotient will be 
\mono{print}ed. \\

\subsection{Bitwise Operators}

Bitwise operators refer to the following: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator} & \textbf{Description} \\
\hline
\mono{<<} & Binary shift left \\
\mono{>>} & Binary shift right \\
\mono{\&} & Bitwise AND \\
\mono{|} & Bitwise OR \\
\mono{\^} & Bitwise XOR \\
\mono{$\sim$} & Bitwise NOT \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

The first two operators are the binary shift operators. The two operands of these operators must be 
integral. As you may know, numbers are represented in binary form internally. The left operand is the 
number to be operated on, while the right operand is the number of bits to be shifted. Let me explain this 
with the help of an example. \\

Say you would like to perform \mono{60 >> 2}. First we convert 60 into binary notation, that is 
$111100_2$ (subscript 2 means representation in base 2, that is, binary). In this example we intend to 
shift 2 bits to the right, that means the two least significant bits (the bits on the far right) are removed, 
and thus resulted in $1111_2$, which is $15_{10}$ in decimal notation, so 15 would be returned. \\

We have used the binary shift right in the example. On the other hand, the binary shift left operator 
does the opposite. It shifts the integer specified left a specific number of bytes, filling the least 
significant bits with 0. Observant readers may notice that each binary bit shift to the left actually
multiplies the number by 2. Try it. \\

The remaining four operators compare the two integral operands bit by bit. As an example, to extract the 
4 least significant bits of the number \mono{\$num}, we can use the expression \mono{\$num \& 15}. The 
returned value is the integral expression of the last 4 bits of \mono{\$num}. The reason is quite simple. 
The binary representation of 15 is $1111_2$. Say \mono{\$num} takes the value of 37 ($100101_2$). The 
operation is shown below: \\

\begin{verbatim}
   1 0 0 1 0 1
&  0 0 1 1 1 1
----------------
   0 0 0 1 0 1
\end{verbatim}

The bitwise AND operator compares each bit. If both corresponding bits are 1, the resulting bit is 1; 
otherwise 0. The above example demonstrates a technique known as \term{bit-masking}, and 15 is the mask 
in this example. To extract specific bits, just set up a mask with the corresponding bits setting to 1, 
and 0 for other bits that we are not interested in. Note that although 15 is only 4-bit long, you may 
consider that it is extended automatically to 6 bits, with the two most significant bits set to 0. \\

The other bitwise operators have the same semantics as their logical operator counterparts except the
truth value is represented by 1 and 0 for true and false respectively. Therefore, the details of which are
not repeated here. \\

Bitwise operators are in general rarely used in most scripts. They are usually only used in applications 
such as cryptography or binary file access. \\

\subsection{Assignment Operators}

Assignment operators refer to the following operators: \\

\begin{center}
\begin{tabular}{cl}
\hline
\textbf{Operator} & \textbf{Description} \\
\hline
\mono{=} & Assignment operator \\
\mono{+= -= *= /= \%= **=} & Arithmetic manipulation with assignment \\
\mono{.= x=} & String manipulation with assignment \\
\mono{\&\&= ||=} & Logical manipulation with assignment \\
%\verb1\&= |= ^= <<= >>=1 & Bitwise manipulation with assignment \\
\mono{\&= |= \^{}= <<= >>=} & Bitwise manipulation with assignment \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}

I have mentioned quite a lot about the ordinary assignment operator \mono{=} in the previous chapters 
already. Now consider this example: \\

\begin{verbatim}
$num = $num + 15;
\end{verbatim}

You should understand what this means, do you? The value stored in \mono{\$num} is added to 15, and the 
result is again assigned to \mono{\$num}. The net effect is to increment the value of the variable by 15. 
However, some people may prefer that manipulation and assignment be accomplished by one, instead of two 
operators. Therefore, Perl recognizes several shorthand notations as shown above. \\

In general, if you can write a statement in this format: \\

\mono{op1 = op1 \textsl{operator} op2;} \\

you can have a shorthand version like this: \\

\mono{op1 \textsl{operator}= op2;} \\

For instance, the example above is identical to \mono{\$num += 15;} However, note that not all the 
operators mentioned above have such a shorthand version. Look at the list above for all the recognized 
shorthand operators. As an example, to invert all the bits in an integral scalar variable (that is, on 
a technical parlance, to assign the ``1s complement'' to the scalar variable), we have to write \\

\begin{verbatim}
$num = ~$num;
\end{verbatim}

\subsection{Other Operators}

Here I shall introduce to you some other operators that do not fit in any of the above main categories.
The operators that would be covered here include the \term{conditional operator} and the \term{range operator}. 
The comma operator and \mono{=>} have already been described in detail in the previous chapter. Putting aside
the builtin functions that may be considered operators in Perl, the remaining operators are \mono{->}, \mono{=$\sim$}
and \mono{!$\sim$}. I have chosen to defer mentioning the remaining operators because they are related to some later 
topics and I would cover them in those sections. The first one, the arrow operator is similar in some sense to the pointer-to-member operator in C.
This would be introduced in the references chapter. The other two are used for pattern matching with regular
expressions. \\

The conditional operator \mono{?:} is a ternary operator. In other words, it has three operands. The syntax is 
as shown below: \\

\begin{verbatim} 
test-expr ? expr1 : expr2
\end{verbatim}
 
The first operand (\mono{test-expr}) is an expression. If this expression evaluates to true, \mono{expr1} will 
be returned by the conditional operator; otherwise, \mono{expr2} is returned. You are likely to use conditional 
operators quite often in the future because it is considered too ``bulky'' to use the \mono{if-else} structure 
all the time. This is an example using \mono{if-else} to compare the values of \mono{\$a} and \mono{\$b}, and 
assign the smaller value to \mono{\$c}: \\

\begin{verbatimtab}[4] 
if ($a < $b) {
    $c = $a; 
} else {
    $c = $b;
}
\end{verbatimtab}
 
By using the conditional operator, this 5-line structure (although no one will stop you from writing all this 
on one line) can be transformed into the simpler statement: \\

\begin{verbatim} 
$c = $a < $b ? $a : $b;
\end{verbatim} 

The following example is extracted from the perlop manpage which demonstrates how the list context 
around the conditional operator propagates to \mono{expr1} and \mono{expr2}. \\

\begin{verbatim} 
$a = $ok ? @b : @c;
\end{verbatim} 

In this example, depending on the value of \mono{\$ok}, the number of elements of either \mono{@b} or \mono{@c} 
is returned and assigned to \mono{\$a}. First, the assignment to \mono{\$a} creates a scalar context around 
the conditional operator. Therefore, the conditional operator is expected to return a scalar value, and so 
the two possible values to be returned will be evaluated in scalar context. \\

Although the conditional operator is inherited from C, there is one important behaviour that is unique to 
Perl. The conditional operator can be assigned to if both \mono{expr1} and \mono{expr2} are legal lvalues. 
This is an example: \\

\begin{verbatim} 
($whichvar ? $var1 : $var2) = $new_value;
\end{verbatim}

In the next section, ``Operator Precedence and Associativity'', we would see an example on how you may 
obtain unexpected results involving the conditional operator because of operator precedence. \\

The behaviour of the range operator (\mono{..}) depends on the context around the operator. The range 
operator actually consists of two disparate operators in list context and scalar context. The range operator 
in list context is more frequently seen, so I will cover it first. \\

I have introduced the range operator in list context briefly in the previous chapter, when I described 
how you can construct an array.  The range operator in list context returns an array consisting of the 
values starting from the left value, with the value of each subsequent element incremented by one until 
the right value is reached. For example, \mono{@array[0..2]} is synonymous with \mono{@array[0,1,2]} to 
return an array slice. Note that both the left and right values would be converted to integer by chopping off 
the decimal portions in case they are not already integers. \\ 

Not only integers can be used in the range operator, you can experiment with alphabets as well. For 
example, ('a' .. 'z') and ('A' .. 'Z') are two lists representing small letters and capital letters, 
respectively. \\

\section{Operator Precedence and Associativity}

Now we have learned several operators, so it's time for us to put them together. It is not uncommon 
that a given statement contains more than one operator. Operator precedence and associativity arise 
as a result. Recall that in elementary Maths class teachers teach us in a mathematical expression 
involving several arithmetic operators, multiplication and division shall be performed before addition 
and subtraction. For example, $3 + 6 \times 7$ is interpreted as $3 + (6 \times 7)$, not $(3 + 6) \times 7$. 
In this case, we say that multiplication and division has higher \term{precedence} than addition 
and subtraction operators. Because multiplication has a higher precedence than addition, the multiplication 
operation, involving the two operands 6 and 7, is performed first, and then the result 42 is added 
to 3, getting 45 as the result. \\

In Perl, because there are many operators, the rules of precedence is far more complicated. In order 
to describe the relative precedence among the operators, most programming languages would use an 
operator precedence table to show the relative precedence of the operators, and Perl is of no 
exception. Table~\ref{tab:ops} shows the operator precedence and associativity table, which you can 
obtain from the perlop manpage. \\

\begin{table}[htbp]
\begin{center}
\begin{tabular}{ll}
\hline
\textbf{Associativity}	& \textbf{Operators}	\\
\hline 
	left 		&	Terms and list operators (leftward) \br \\
	left 		&	\mono{->} \br \\
	nonassoc	&	\mono{++ --} \br \\
	right		&	\mono{**} \br \\
	right 		&	\mono{! $\sim$ \textbackslash\ + -} (unary) \br \\
	left 		&	\mono{=$\sim$ !$\sim$} \br \\
	left 		&	\mono{* / \% x} \br \\
	left 		&	\mono{+ - .} \br \\
	left 		&	\mono{<< >>} \br \\
	nonassoc	&	named unary operators \br \\
	nonassoc	&	\mono{< > <= >= lt gt le ge} \br \\
	nonassoc	&	\mono{== != <=> eq ne cmp} \br \\
	left 		&	\mono{\&} \br \\
	left 		&	\mono{| \^} \br \\
	left 		&	\mono{\&\&} \br \\
	left 		&	\mono{||} \br \\
	nonassoc	&	\mono{.. ...} \br \\
	right		&	\mono{?:} \br \\
	right 		&	\mono{= += -= *= } etc. (assignment operators) \br \\
	left		&	\mono{, =>} \br \\
	nonassoc	&	List operators (rightward) \br \\
	right		&	\mono{not} \br \\
	left		&	\mono{and} \br \\
	left		&	\mono{or xor} \br \\
\hline 
\end{tabular}
\\[\baselineskip]
\end{center}
\caption{Operator Precedence and Associativity Table}\label{tab:ops}
\end{table}

The operators are arranged in order of decreasing precedence. That is, the operators at the top (Terms and 
List Operators) have the highest precedence, while the operators at the bottom (\mono{or}, \mono{xor}) have 
the lowest precedence. Operators on the same line have the same precedence. \\

The first column lists the \term{associativity} of the operators. Associativity is useful when there are 
several operators of the same precedence in a statement. In this situation, the order of evaluation of 
these operators depends on the associativity. If the associativity is right, then the rightmost one would 
be evaluated first, then the one on the left, and so on. That's why cascaded assignment is possible. The 
idea is the same for left associative. You may also find that some operators are labelled ``nonassoc'' 
(non-associative). The operators are classified as non-associative if the order of evaluation is not 
important, or not applicable for other reasons. In general, you don't have to worry about the order of 
evaluation of the non-associative operators really much. \\

To demonstrate the effect of operator precedence and associativity, let's go over several scripts here. \\

\begin{verbatim} 
#!/usr/bin/perl -w

$, = "\n";
$a = 13, $b = 25;
$a += $b *= $c = 35 * 2;
print "\$a == $a, \$b == $b, \$c == $c";
\end{verbatim}

This one is practically easy. I would use it to illustrate how precedence and associativity works. 
The problematic statement is on line 5, and you shouldn't have problems with the rest of the script, 
so I am focusing on this line only. To deal with this statement, first try to locate the operators concerned. 
The operators, by scanning from left to right, are: \\

\begin{verbatim} 
	+=  *=  =  *
\end{verbatim}

Now locate the operators with the highest precedence, and it is \mono{*} in this case. Therefore, 
multiplication would be performed first. The operands of this operator are 35 and 2, so this multiplication 
yields 70. The remaining are all assignment operators having the same precedence, so we look at their 
associativity. Because the associativity is right, the rightmost one is evaluated first, which is \mono{=}. 
The operands are \mono{\$c} and 70 (the value of the expression 35 $\times$ 2), so 70 is assigned to \mono{\$c}. 
Then, \mono{\$b *= 70} is evaluated, and \mono{\$b} is eventually assigned 1750 (70 $\times$ 25). At last, 
\mono{\$a += 1750} causing \mono{\$a} to be assigned 1763. \\

There is not much confusion here, but let's consider another more tricky example, of which the result is not
necessarily apparent at first glance. \\

\begin{verbatim} 
#!/usr/bin/perl -w

$, = ", ";
$a = 1, $b = 0;
print $a >= $b ? $b : $a += 6, $a;
\end{verbatim}
 

I first saw a similar example from a C++ book, and I adapted it to become a Perl script. This is a really 
notorious example, because it includes \mono{?:}, which easily leads to unexpected result if you are not 
careful enough. I hope you could understand my explanation as this example, though seemingly short, is so 
notorious that it is rather difficult for me to explain it well. \\

Now let's have a quiz: without actually running it with your perl interpreter, try to deduce the printout
of this example. Let's give you two choices: \\

\begin{enumerate} 
\setlength{\itemsep}{-0.15cm}
\item 0, 1
\item 6, 1
\end{enumerate} 

(don't look at the answer below before you have an answer in your mind) \\

If you choose option A, I'm sorry, you're wrong. But don't despair, as many people share the same mistake 
as you do, and it is common and understandable for people to make mistakes. Although novices are more prone 
to make mistakes, nothing will stop veterans from making mistakes as well. Most computer programs we are 
using have bugs. Some bugs are obvious, but there are many more hidden ones which are not normally revealed 
unless your program gives unexpected output. Trust me, debugging is going to occupy most of your development 
time, and is the most tedious job for all programmers. If you choose option B, congratulations, you are correct. 
Hope that you did not get the correct answer by sheer guesswork. Anyway, let's look at how we arrive at the answer. \\

If you choose option A, you may have the impression that \mono{+=} has a high precedence, but this is not 
the case. In this example, \mono{?:} also exists, which has a higher precedence than \mono{+=}, so \mono{?:} 
is evaluated before \mono{+=}. Here comes the trouble. The operators, scanning from left to right, are: \\

\begin{verbatimtab}[4] 
	print  >=  ?:  +=  ,
\end{verbatimtab} 

\mono{print} is a list operator, and has the highest precedence. So Perl looks on the right hand side for 
its parameters. Then Perl sees \mono{>=}, which has the second-highest precedence. So \mono{\$a >= \$b} is 
then evaluated, yielding true. Among the remaining operators, \mono{?:} is the highest. The problem is, 
what are its operands? As you have learned, this operator has three operands, the so-called ``test'' part 
(that is \mono{\$a >= \$b}, and have found to be true), the ``true'' part (\mono{\$b}), and the ``false'' 
part. But wait! What is the false part? \mono{\$a} or \mono{\$a += 6}? Its the former one, in the contrary 
to what you may have expected. \\

As Perl scans from left to right to find the false part, it encounters the \mono{+=} operator, which has a 
lower precedence than \mono{?:}, and Perl stops and claims that the false part is \mono{\$a}. Then Perl 
knows what to do, so evaluates the conditional operator, returning the true part, that is \mono{\$b} (that 
holds the value 0). Anything left? Yes, we still have the dangling \mono{+= 6} part! It is tricky that the 
conditional operator returns an lvalue if it can, and so \mono{\$b += 6} is evaluated, causing \mono{\$b} 
to hold the value 6 instead. We have finished evaluating the first argument to the print operator, and the 
second operand is \mono{\$a}, which has been untouched. That's how we arrive at the answer ``6, 1''. \\

Troublesome enough? Two long paragraphs just to explain one statement. If you are still scratching your head, 
try to read these two paragraphs repeatedly until you understand. So you see, operator precedence and 
associativity can trip you up if you are not careful. \\

But what if this is not your intention? What if you'd like to have \mono{\$a += 6} as your false part? 
Recall how you do this in arithmetic --- adding a pair of parentheses. This applies to Perl as well. This 
is easily done as this: \\

\begin{verbatimtab}[4] 
 print $a >= $b ? $b : ($a += 6) , $a;
\end{verbatimtab} 

In Perl, parentheses are treated as ``terms'', which has the highest precedence in the precedence table. 
This ensures that all expressions in parentheses are evaluated before other operators do. Parentheses is 
the cure for those who enjoy writing complicated statements but wouldn't like to memorize (or consult) the 
operator precedence table. Adding parentheses appropriately not only eliminates a great deal of effort when 
you or other programmers read your code at a later time, many unexpected errors could be eliminated as a 
result. But sometimes parentheses do not add much clarity to your code. Here's an example: \\

\begin{verbatimtab}[4] 
	print(lc(shift(@MyArray)));
\end{verbatimtab} 

In this example, all but \mono{print} are named unary operators. Because named unary operators have only one 
parameter, in general there is not much confusion if you just omit the parentheses. In conclusion, use 
parentheses wherever appropriate. Feel free to insert parentheses as you see fit to minimize confusion but
don't overdo it. \\

There are several points to note arising from this example. 
First, although looking na\"ive to mention here, whitespace is NOT a determinant of the order of evaluation. 
You definitely cannot write the above statement in this way and expect it to work the same way the parenthesized version does: \\

\begin{verbatimtab}[4]
	print $a >= $b ? $b :$a+=6   , $a;
\end{verbatimtab}

This is actually the same as line 5 in the example! So it returns ``6, 1'', not ``0, 1''. This is because when 
the Perl interpreter loads the script, it parses it and removes all intervening whitespace automatically. \\

Second, you have to be careful about the use of parentheses. Consider these examples: \\

\begin{enumerate}
\setlength{\itemsep}{-0.15cm}
\item \mono{print 1+2+3;}
\item \mono{print (1+2+3);}
\item \mono{print 1+(2+3);}
\item \mono{print (1+2)+3;}
\item \mono{print(1+2)+3;}
\end{enumerate}

In the above examples, statements A--C would give the correct answer, 7, while the last two would give 3. 
Statements A and B have nothing special. In statement D, however, because the opening brace is placed 
immediately after the operator, Perl thinks that this pair of parentheses contain all the parameters to be 
sent to the operator. In this case, \mono{1+2} is its only argument, so 3 is printed. Because the \mono{print}
operator returns nothing, thus leaving the dangling part ``+3'' for Perl to evaluate. Since this is a 
useless addition operation, a Perl warning would be displayed if you have warnings enabled. Statement E 
is the same as D (recall that whitespace does not matter?). \\

For statement C, because you do not have an opening brace immediately following it, Perl does not think 
that there are parentheses to contain the parameters as in statement D. The parentheses in statement C 
is treated in the normal way, that is, evaluated first, and then the lower-precedence operators. \\

Third, notice that in the operator precedence charts there are two entries for list operators. List operators 
(leftward) in this tutorial (and in the perlop manpage) refer to the name of the list operator concerned. Such 
a high precedence allows Perl to know where such operators occur, so that it knows where to look for their 
parameters. On the other hand, list operators (rightward) applies to the comma-separated expressions to pass 
to the list operator concerned as parameters. The extremely low precedence of this part implies that you do 
not normally need to put parentheses around the parameters. This part acts figuratively like a basket 
containing all the parameters. The only operators having lower precedence are the operators \mono{not}, 
\mono{and}, \mono{or} and \mono{xor}. For example, \\

\begin{verbatimtab}[4] 
	open HANDLE, "$path/.bash_history" or die "Can't open file\n";
\end{verbatimtab} 

Because \mono{or} has a lower precedence than list operator (rightward), the \mono{or} part is not treated 
as part of the operand for the \mono{open()} operator. In the example, if the \mono{open} operation fails, 
it returns \mono{undef}, which is interpreted as false. Because short-circuit evaluation is not possible, 
the second part is executed, which outputs the error message and terminates the script. You would learn how 
to open files later on in this tutorial. \\
 
\section{Constructing Your Own \mono{sort()} Routine}

In the last chapter you have had an overview of using the \mono{sort()} function to sort a list of values. I also
provided you with a list of common search routines. By now you should have sufficient knowledge to understand the
rest of the story. \\

The principle is pretty simple but rather difficult to visualize. You override the default sort criteria
by defining the ordering criteria in the code block of the \mono{sort()} function. Two special variables \mono{\$a} and 
\mono{\$b} are defined in the block. In order to sort a list of values, the sort routine needs to establish the
total ordering of any two arbitrary items in the list. To do so, it assigns the two items to \mono{\$a} and \mono{\$b}
arbitrarily. The block should perform some comparison operations in the block based on these two values. If evaluation of the block yields
a scalar value that is negative, the value held by \mono{\$a} comes before that of \mono{\$b}. If the result
is positive, the value held by \mono{\$b} comes before that of \mono{\$a}. If the result is zero, then
the two values should be considered equal. The \mono{<=>} and \mono{cmp} operators are usually used.
The following is an example which illustrates numeric descending sorting. \\

Assume the unsorted list is \mono{(3, 1, 4)}. To sort in descending numerical order, an appropriate 
expression which satisfies the above characteristics is \\

\begin{verbatim}
$b <=> $a
\end{verbatim}

The following table illustrates how you can try to verify if the comparison works. 3 $\rightarrow$ 1 below 
means 3 comes earlier than 1 in the resulting list. \\

\begin{table}[htbp]
\begin{center}
\begin{tabular}{cccc}
\hline
\textbf{\mono{\$a}}	& \textbf{\mono{\$b}} &	\textbf{\mono{\$b <=> \$a}} & \textbf{Ordering}	\\
\hline 
	3	&	1	&	-1	&	3 $\rightarrow$ 1 \br \\
	1	&	4	&	1	&	4 $\rightarrow$ 1 \br \\
	3	&	4	&	1	&	4 $\rightarrow$ 3 \br \\
\hline
\end{tabular}
\end{center}
\caption{An Example Illustrating \mono{sort()}}\label{tab:sort}
\end{table}

Therefore, the ordering 4 $\rightarrow$ 3 $\rightarrow$ 1 is established. \\

\section*{Summary}

\begin{summary}
\item Operators carry out certain operations on data, known as operands.
\item An expression consists of a combination of operators and operands.
\item Unary, binary and ternary operators take on one, two and three operands respectively. List operators can take on a variable number of operands.
\item In Perl, functions are simply treated as unary or list operators.
\item Arithmetic operators carry out arithmetic calculations.
\item Assignment operators are used to assign scalar or list value to a data structure.
\item Comparison operators compare two pieces of scalar data and returns a Boolean value.
\item Equality operators are specializations of comparison operators which test if two pieces are considered equal.
\item Bitwise operators can be used to perform binary arithmetic.
\item Logical operators operate on Boolean values.
\item String manipulation operators involve string concatenation operations.
\item Operator precedence and associativity determines the order in which operators are evaluated in an expression.
\item The \mono{sort()} function sorts a list of scalar values. Ordering is determined by the return value of the code block provided in the \mono{sort()} function.
\end{summary}
