\chapter{Conditionals, Loops \& Subroutines\label{chap:scope}}

% ====================================================================== 

\section{Breaking Up Your Code} 

So long you have been writing your programs in one piece. You are totally allowed to carry on with this practice, 
however, lumping everything in one piece is often considered undesirable for the following reasons: \\

\paragraph{Ease of maintain} 
A single source file with tens of thousands of lines is for sure not easy to maintain. First, navigating around
in the source file is messy --- page up and page down keys are unlikely to be effective for files of this size
and to locate a certain section of code much traversal is necessary. \\

\paragraph{Variable Conflicts}
Variable management is not a trivial affair in practice when the program is a large one. It is easy for us to
keep track of the variables in use for short programs we have been writing for now, but shortly when the
code base grows in size, it becomes increasingly likely that variable name clash occurs at certain parts of the
source code. That is, you use a variable that is defined somewhere else but you are unaware of it. This may give
rise to some unexpected behaviour that are difficult to debug. Object-oriented programming is a desirable
solution. We would discuss the concepts of scope and packages, which are fundamental to object-oriented programming
that would be covered in the next chapter. \\

\subsection{Sourcing External Files with \texttt{require()}}

The \texttt{require()} function can be used to source external files. It acts in this way --- when execution
reaches a \texttt{require()} statement, it first checks if the file has already been \texttt{require}d. This is to
avoid multiple inclusions and potential file inclusion loops (for example, A includes B, and B includes A etc.). \\

The predefined variable \texttt{@INC} stores path prefixes the Perl file inclusion system use to find
the file to be sourced. You may type the following command at the command prompt to output the content of \texttt{@INC}: \\

\begin{lstlisting}[numbers=none]{}
perl -e 'print map {"$_\n"} @INC;'
\end{lstlisting}

On my Linux system, the list of paths is, in ascending order, \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground},numbers=none]{}
cbkihong@cbkihong:~/public_html> perl -e 'print map {"$_\n"} @INC;'
/usr/lib/perl5/5.8.0/i686-linux-thread-multi
/usr/lib/perl5/5.8.0
/usr/lib/perl5/site_perl/5.8.0/i686-linux-thread-multi
/usr/lib/perl5/site_perl/5.8.0
/usr/lib/perl5/site_perl/5.6.1
/usr/lib/perl5/site_perl
.
\end{lstlisting}

There are 7 entries. The last entry is a single dot denoting the current directory. Note that the 
paths listed are likely to be different on each system. They are fixed in the Perl installation process. \\

\texttt{require()} is an overloaded function serving three purposes:
\begin{itemize}
\item If the argument is a number, it checks
if the perl interpreter version (\texttt{\$]}) is greater than the version specified as the argument. This use 
generally appears in Perl modules to specify the earliest perl interpreter version with which the module can be executed; 

\item If it is a 
bareword, that is not enclosed in quotation marks, it is assumed to be the package name of a module with extension ``.pm'' (see Chapter~\ref{chap:oop})
and any occurrences of `::' are converted to `/' on Unix-variant OSes or `\textbackslash' on Windows or MS-DOS.
The result is a relative path to a Perl module; 

\item If the argument is a quoted string, it is treated as the relative path to the file to be included.
\end{itemize}

For the last two cases, the relative path resulted is appended to each of the paths in \texttt{@INC} in turn to
form a complete path and \texttt{require()} checks if a file exists at this location. The first file that is found 
is used. As you can see, the system modules directories are searched first, and at last the current directory is
searched. \\

If the search yields an existing file, the relative path is added to \texttt{\%INC} as the key while the complete
path formed as the value.  The \texttt{\%INC} hash variable is maintained by Perl which contains a list of 
files included. Whenever you invoke the \texttt{require()} function, it 
checks this hash to determine if the file specified already exists in \mono{\%INC}. If it does not, an entry is 
added to it; otherwise, the inclusion is silently bypassed. \\

For example, say you have a source file which has the following \mono{require()} statements: \\

\begin{verbatim}
require 'myfile.pl';
require MyModule;
\end{verbatim}

The \mono{require()} function will append the key-value pairs \\ 

\begin{verbatimtab}[4]
(
	'myfile.pl' => '/home/cbkihong/somedir/myfile.pl',
	'MyModule.pm' => '/home/cbkihong/somedir/MyModule.pm',
)
\end{verbatimtab}

to \mono{\%INC}. Consider the situation if inside the module \mono{MyModule} it also tries to \mono{require 'myfile.pl'}, 
because an entry with the key `myfile.pl' already exists in the hash, this inclusion is bypassed. Therefore, 
multiple file inclusions can be detected and avoided. \\

If the file \mono{require}d does not return a true value (as a recapitulation --- 
anything other than 0, an empty string or \texttt{undef}), \texttt{require()} fails with an error. Perl module
authors may utilize this characteristic to abort the scripts using the module in case of errors. Therefore, you
ought to see in later chapters that external files usually terminate with the statement \mono{1;} which returns
the true value required. \\

The description above is a rewrite of the \link{http://www.perldoc.com/perl5.8.0/pod/func/require.html}{\texttt{require()}}
manpage. It is easy to understand and you are advised to read it for further information. In Chapter~\ref{chap:oop} you
would learn the \texttt{use()} operator which is a wrapper of \texttt{require()} and is used to load Perl modules. \\

% ====================================================================== 

\section{Scope and Code Blocks}

\subsection{Introduction to Associations}

Consider this simple assignment statement: \\

\begin{verbatimtab}[4]
	$fruit = "apple";
\end{verbatimtab}

How would you describe this statement? The string ``apple'' is assigned to the scalar variable named
\texttt{\$fruit}. Fine, this is how the statement is interpreted literally, but this description is 
not sufficient as you progress through the following chapters. A better and more in-depth way of expressing
this statement is that a data object with the scalar value ``apple'' is created, and the name ``fruit'' is
now associated with this data object. Why do we have to bother with this expression? Because up to now
we have been writing programs with each data object associated with one and only one name, which is the
name of the variable. However, in this chapter we would see that due to scoping rules the same name at
different parts of a program can be associated with different data objects. This \term{association} is
also known as a \term{binding}. In the next chapter we would 
introduce to you the possibility of establishing additional associations to a data object, which are 
references. Therefore, from now on you need to have a clear separation of the data object and its name 
associations. \\

\subsection{Code Blocks\label{sec:scope}}

The idea of confining the scope of associations arose from the fact 
that not all variables need to be valid throughout the lifetime of the program. This is particularly important 
in subroutines, which are self-contained reusable units containing a sequence of statements. \\

The \term{scope} of an association refers to the region in a program in which the association is visible. 
Up to the present, we have been writing very simple scripts with scalar variables, arrays and hashes which,
once created, could be used anywhere in the script. What we have been using in our examples so far are all global variables, in the
sense that all associations are established during the compilation phase before execution, and are not
destroyed until the program terminates because these variables are resolved from the symbol table, which
exists as long as the program is in execution.  
Note that once you have created an association there is no way for you to manually destroy it. An association will only be 
destroyed when the scope in which it resides terminates. In this sense, a global variable has a global scope.
Excessive use of global variables is considered a poor programming practice, 
because as your program becomes increasingly complicated, it is not impossible that your program may involve 
dozens to even hundreds of variables. Perhaps you may need some of them to be accessible throughout the whole 
script, but this is not generally the case. In particular, many variables are simply used to store data 
temporarily, for example, as a counter in a loop (as you will see later in this chapter). %
Introduction of limited scopes is seen as a cure to the problem. \\

%\p{Note that once you have created a variable there is no way for you to expire it. A variable will only be 
%destroyed when the scope in which it resides terminates. A global variable has a global scope, that is it would 
%be destroyed only when the script terminates. Therefore, in order to establish a local variable, we need to 
%create a scope and restrict the variable within the scope.}

Scopes are defined in terms of \term{environments}. An environment is created by means of a
\term{code block}, or simply, a block. A code block simply consists of a sequence of statements that 
makes up an environment, and is delimited by curly brackets (but the
mere presence of \texttt{\{ \}} doesn't necessarily imply a code block --- you will see \texttt{do\{\}} and 
\texttt{eval\{\}} later in this chapter that look like blocks, but they are not strictly one). Code blocks can be nested. In
other words, one code block can appear in another code block. Like this: \\

\begin{verbatimtab}[4]
# Environment A
{
	# Environment B 
	{
		# Environment C
	}
	# Environment B resumes
	{
		# Environment D
	}
	# Environment B resumes
}
# Environment A resumes
\end{verbatimtab}

As you can see, after \texttt{\{} a new environment is started. When \texttt{\}} is reached, 
the current environment terminates, and the parent environment, that is, the environment that 
was previously in effect is reinstated. For example, when environment C terminates, environment B will 
resume.  With \texttt{my} and \texttt{local} modifiers that 
we are going to explore in the next section, you can confine the scope of an association to within the extent 
of an environment --- when the containing code block terminates, the association would be destroyed. \\

\specialbox{NOTES}{%
Please interpret the above statement carefully. Although all associations are destroyed when the current environment
terminates, this does not necessarily mean the objects themselves are destroyed. This is related to the garbage collection 
mechanism in Perl, which will be covered in the next chapter when we come to references. In particular, if 
additional references to the object exist, the object will not be destroyed. \\
}

% ====================================================================== 

\section{Subroutines}

Breaking up your source code into multiple files is not the only way you can make your code more manageable. A
complex program can be broken into smaller tasks, each of which carries out a well-defined function.
Take an online book catalogue served in a typical library as an example, you can actually split the whole 
complicated program into smaller parts. For example, these are the functions that may be implemented in such 
a system: \\

\begin{itemize} 
\item Search the catalogue by title, author, keywords, etc.
\item Allows users to check their circulation record
\item Allows users to reserve or renew items
\item Perhaps to send a reminder to a borrower automatically if he forgets to return the borrowed items on time
\end{itemize}

You should be able to think of many more, but this already exemplifies a program will be easier to write and 
manage if you break it up into smaller and simpler parts, with each part doing its intended task only. This shows 
how useful subroutines are. A \term{subroutine} consists of a sequence of statements defining an environment. 
Subroutines are just like user-defined functions in contrast to those provided by Perl. There
are two types of subroutines --- named subroutines and anonymous subroutines. Anonymous subroutines are not
given a name while named subroutines are. We shall cover anonymous subroutines in Chapter~\ref{chap:ref} when 
we come to the topic of references. From now on, by means of subroutines we refer to named subroutines. \\

\subsection{Creating and Using A Subroutine}

In general, before we can call a subroutine, we need to declare and define it. Declaring the subroutine makes
Perl aware that a subroutine of a particular name exists. Defining means 
you explicitly describe what the subroutine does by listing the statements to be executed if the subroutine is 
being called. \\

In general, subroutine declaration and definition go together. The syntax used to declare and define a subroutine 
is as follows: \\

\texttt{%
\textbf{sub} name \textsl{\textcolor{optionalargs}{[\textbf{(}prototype\textbf{)}]} block}
} \\

\mono{block} is the subroutine definition. It is a code block containing the statements to be executed when the 
subroutine is invoked. The rest is the subroutine declaration. It declares a subroutine with the name \mono{name}.
After the subroutine name you may insert an optional \mono{prototype} part which contains a concise specification of
the types of parameters to pass to the subroutine. \\

Here is an example using a subroutine to calculate the sum of a list of scalars (presumably numeric): \\

\head{EXAMPLE}{}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/eg0502.pl}
 
Lines 3-11 contain the declaration as well as the definition of the subroutine \texttt{sum()}. Line 3 tells Perl 
that you are declaring a subroutine named \texttt{sum}, while lines 4-10 are the subroutine definition. Subroutines 
have to be declared and defined before being called in the script. If you place the \texttt{print} 
statement (line 14) before the subroutine declaration, your script simply won't work as expected. This is because 
the perl interpreter reads your script sequentially. If it encounters the token \texttt{sum} before it is declared, 
Perl will not know \texttt{sum} is a user-defined subroutine as Perl cannot find it in the system libraries. That
implies you should, in principle, always put subroutine declarations and definitions very early in source files. 
As you can see in the example, the subroutine is put before the source program that calls it. However, this may not
be convenient sometimes. For example, when you have multiple subroutines which are inter-dependent on one another,
it may not be convenient for you to find out a proper order of declaring the subroutines. Therefore, Perl allows 
you to make forward declarations, at which point the subroutines are declared but not defined. Forward declarations
are put at the very top to declare the subroutines, and somewhere later on you give the definitions of the subroutines
concerned, which can then be placed in any order. In the example, in order to make a forward declaration of the \texttt{sum} 
subroutine, it can be made like this: \\

\begin{verbatim} 
sub sum(@);
\end{verbatim}

This statement tells Perl in advance (before parsing the subroutine definition) that \texttt{sum} is the name of a 
subroutine accepting a variable number of scalars as arguments, and Perl will know to look for the definition of 
\texttt{sum} in the later part of the program. The forward declaration is the same as the declaration line except 
we replace the block containing the definition with a semicolon. \\

Although you may not understand the \texttt{my} modifier and the \texttt{for} loop in the script at the moment, 
you may ask a question: why do I have to resort to subroutines if I can implement it directly with a \texttt{for} 
loop or a \texttt{foreach} loop? Well, note that the subroutine \texttt{sum} serves a general purpose. It adds 
up all the input values and return the result, regardless of the values of the input. Therefore, this subroutine 
is highly versatile and flexible --- it can be used directly without modification on any occasion you would like 
to evaluate the sum of a list of scalars. If you write the script as follows, it can only be used to sum up all 
the integers between 0 and 100. Whenever you would like to evaluate a sum of something else, you have to rewrite the code: \\

\begin{lstlisting}[numbers=none]{}
# calculates 0 + 1 + 2 + ... + 100 and prints the value
my $sum = 0;
for my $tmp (0 .. 100) {
    $sum += $tmp;
}
print $sum;
\end{lstlisting}
 
By writing your code in subroutines, you are enforcing \term{reusability} of your code. Code reusability is 
important as we wouldn't like to write similar pieces of code again and again. Later on you will learn how to 
build reusable modules where you can put your subroutines and save them as a file so that whenever you need to 
use the subroutines in another project, you just need to import the module, and the subroutines can be reused in 
your new project. This is very convenient. Here is how the \texttt{sum} subroutine can be readily applied to 
evaluate the sum in other situations:

\begin{verbatimtab}[4] 
print sum values %score;  # print the sum of the values of %score  
$avg = sum(@nums)/@nums;  # evaluate the average of the values of @nums 
\end{verbatimtab}
 
Apart from improved reusability, subroutines also help make debugging easier. Once we are certain that a 
subroutine is correct, we can safely apply it. It is likely that fewer number of errors would be committed when 
we combine the subroutines to form an entire program than writing it without using any subroutines. \\

Unlike other languages like C or Java, Perl does not support named parameters. All incoming parameters are combined
into one indistinguishable array \mono{@\_}. The first parameter is thus \mono{\$\_[0]}. Therefore, if you have a
mixture of arrays and scalars the elements of which would be combined into \mono{@\_}. You may use pass-by-reference
to be discussed in the next chapter to avoid it. \\

Also, note that the elements of \mono{@\_} are not copied by value. The elements of \mono{@\_} are ``references''
to the data values. They behave like references but do not look like references in terms of syntax. Basically, the
idea is when you modify a value of an element in \mono{@\_}, the corresponding data object will be modified as well.
Consider this example: \\

\begin{lstlisting}[numbers=none]{}
sub test {
	$_[2] = 5;
	$_[3] = 6;
}

my @a = (1, 2, 3);
my $b = 4;
test(@a, $b);
print join(', ', @a, $b), "\n";		# 1, 2, 5, 6
\end{lstlisting}
 
Here, when the third as well as the fourth element of \mono{@\_} are updated, the corresponding elements in \mono{@a}
and \mono{\$b} will be modified. What if we replace \mono{\$b} with the literal $4$? Now because the data object cannot
be modified, it will be an error. In principle, changing the value of parameters silently in a subroutine is a bad
programming practice, although sometimes you cannot avoid it. You should document these cases clearly, for example, as 
comments in the source files. \\

Because a parameter can be inadvertently modified in a subroutine, in general, you should not use the elements of 
\mono{@\_} directly in scripts. You can use the following technique: \\

\begin{lstlisting}[numbers=none]{}
sub search {
	my ($myitem, @myarray) = @_;
	# use $myitem and @myarray thereafter
	# ...
}

my @array = (1, 2, 3);
my $searchFor = 2;
search($searchFor, @array);
\end{lstlisting}

By using the \mono{my} modifier, \mono{\$myitem} and \mono{@myarray} are confined to within the \mono{search} subroutine
only. Here, the elements are copied by value to  \mono{\$myitem} and \mono{@myarray}. Therefore, the tie between them 
and the original data objects no longer exists. Even if you inadvertently modify the values or \mono{\$myitem} or 
\mono{@myarray}, the changes won't be made to the original data objects. Moreover, this emulates named parameter
passing in other programming languages. \\

A subroutine may return a list of values to the caller. As shown in Example~5.1, this is achieved by the \mono{return}
function. A subroutine may return a scalar or a list of scalars. Similar to the case for incoming parameters, multiple
arrays or hashes are combined into one single list. Again, you may use references to circumvent this, though. \\

\subsection{Prototypes\label{sec:prototype}}

%From a user's perspective, a subroutine is intended to function like a ``black-box''. That is, 

Recall that while declaring a subroutine you may put an optional prototype specification. It describes the number of as well as the type of parameters 
in a compact form. The prototype gives Perl a clue as to how the arguments should be handled. Having an accurate
grasp of the types of arguments expected is important, as illustrated in a mini case study below. \\

The prototype specification comprises a sequence of symbols indicating the type of each argument. The symbols should
look familiar to you, because they are the same symbols which are used to denote scalar variables, arrays, hashes etc. 
In front of each symbol you may prepend a backslash \textbackslash\ to indicate the element is to be passed by reference.
This is covered in the next chapter. \\

\begin{center}
\begin{tabular}{cc}
\hline
\textbf{Symbol}	&	\textbf{Type}	\\
\hline 
\texttt{\$}		&	Scalar variable \br \\
\texttt{@}		&	Array \br \\
\texttt{\%}		&	Hash \br \\
\texttt{\&}		&	Anonymous subroutine \br \\
\texttt{*}		&	Typeglob (Reference to Symbol Table entry) \br \\
\hline
\end{tabular}
\end{center}

For example, if the prototype is \texttt{(\$\$)}, that 
means the subroutine accepts two scalar variables as parameters. \texttt{(\$\$@)} implies the first two parameters 
to be evaluated in scalar context while the remaining parameters would be grabbed by an array variable. Note that 
you cannot have something like \texttt{(@\$)} as the array variable (or hash variable alike) would take up all the 
input parameters. Always bear in mind that multiple parameters, after evaluating in their respective contexts, 
are combined together to become one indistinguishable array \texttt{@\_}. \\


A ``programmer'' who claimed to know Perl was asked by his boss to write a subroutine which inserts a list into an array at a certain position. 
There is already a \mono{splice()} function which can do that for him, so he decided to write a wrapper which calls \mono{splice()}
to do the job. The boss, as a user, would like to use the subroutine in this format: \\

\texttt{
\textbf{insert} @array, \textsl{pos}, \textsl{list}
} \\

which is identical to the syntax of \mono{splice()} except without the length parameter. The ``programmer'' wrote this: \\

\begin{verbatimtab}[4]
sub insert {
	# !!WARNING!! This does NOT work!
	my (@myarray, $pos, @list) = @_;
	return splice(@myarray, $pos, 0, @list);
}
\end{verbatimtab}

Without even trying it, he handed it to his boss. The boss tried to use it in this way: \\

\begin{verbatim}
@array = (1, 2, 3);
insert(@array, 3, 4, 5, 6);
\end{verbatim}

It didn't work, and he lost his job. Does that sound too stupid for you? Why doesn't it work? As I have reiterated
a number of times already, because all the parameters are combined into a single list when they are passed to the
subroutine. You can't really separate them back into the three parameters, because the first argument is an array
which due to its ``greediness'' would take all the elements passed into the subroutine, leaving \mono{\$pos} and
\mono{@list} undefined. The proper way to do this is: \\

\begin{verbatimtab}[4]
sub insert (\@$@) {
    my ($array, $pos, @list) = @_;
    return splice(@$array, $pos, 0, @list);
}
\end{verbatimtab}

It uses both pass-by-reference with a prototype added to make the types of parameters expected explicit.
The use of \mono{@\$array} causes the original array to be modified, as we'll cover in the next chapter.
As for the prototype, we indicate the parameters are an array reference, a scalar and then a list. If a
subroutine has a prototype, Perl will try to evaluate the parameters according to the prototype. Consider
the case if the boss uses the subroutine in this way: \\

\begin{verbatim}
@array = (1, 2, 3);
insert(@array, @array, 4, 5, 6);
\end{verbatim}

This is identical to the previous case. Note that in the prototype the second parameter indicates a scalar
is expected. Therefore, a scalar context is put around \mono{@array} which causes the number of elements
in \mono{@array} to be passed as the second parameter, which causes the list specified to be appended to the end of
the \mono{@array}. \\

You can also specify optional parameters. Compulsory parameters are separated from optional parameters by adding 
a semicolon in between. For example, say you have a subroutine whose declaration statement is 
\texttt{sub mysub (\$\$;\$\$);}, and you make the following subroutine call: \\

\begin{verbatim} 
mysub @array, "3", 9;
\end{verbatim} 

Because \texttt{@array} is evaluated in scalar context, \texttt{@\_} is the list \texttt{(scalar(@array), "3", 9)}. 
The fourth parameter is empty. By using prototypes you can let Perl check parameter types and evaluate the parameters 
in the correct contexts. \\

A sidenote about subroutine invocation. Traditionally, subroutines had to be prefixed with the \mono{\&} symbol
when invoked, and the parentheses are compulsory in this case. For example, \mono{\&mysub(@array, "3", 9);} 
When a subroutine is invoked in this way, the prototype is ignored. Therefore, I recommend not to use the \mono{\&}
form in general. A few situations where you need to use the \mono{\&} form will be covered in the next chapter. \\


\subsection{Recursion}

\term{Recursion} is more of a technique rather than a feature of a programming language. It refers to the practice
of tackling a problem through dividing it into smaller sub-problems and tackling them independently. Each of these 
sub-problems may also be subdivided if necessary. In programming languages, recursion is typically achieved through
nested invocation of a subroutine, directly or indirectly. We'll examine recursion with the help of an example. \\

A palindrome is a sequence of characters that is identical regardless you read it in a forward or backward direction.
For example, ``dad'' and ``sees'' are examples of palindromes. Here, we tackle the problem of determining whether
a given string is a palindrome. For simplicity, we only consider strict palindromes that are symmetric character 
by character. Phrases like ``Madam, I'm Adam'' are generally considered palindromes, but we don't classify them as such. \\


There are (at least) two ways to tackle this problem, namely the iterative and recursive approach. 
First, we present the source program for the iterative approach: \\

\head{EXAMPLE}{Palindrome}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/palindrome1.pl}
 
Then the recursive approach: \\

\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/palindrome2.pl}

The only part of concern is the subroutine definition of \mono{isPalindrome()}. In the iterative approach,
two pointers are maintained which initially point to the first and the last character, respectively. 
A loop is set up which iterates as the pointers move towards each other. When an unmatched character pair is found
the value 0 is returned, which signifies the string is not a palindrome. Finally, when the positions of the left pointer and 
right pointer are swapped, that implies the entire string has already been scanned through and all character pairs
matched (or 0 would have been returned), so we can then conclude the string is a palindrome. \\

The logic behind the recursive scheme, however, seems to be cleaner and more intuitive. In the iterative approach, 
a single \mono{isPalindrome()} invocation tackles the whole of the problem. However, the recursive approach suggests
to break this problem into multiple levels. At each level, we merely compare the first and last character of the
incoming string. The string in the middle is passed to a new invocation of \mono{isPalindrome()} to deduce whether
it is a palindrome. In other words, we define that a palindrome is one whose first and last character are identical 
and the substring in the middle is also a palindrome. If both conditions are satisfied we conclude the string is 
a palindrome; otherwise, it isn't. \\

Lines 21-23 in the recursive example handles the case when the incoming string is a single character or an empty 
string. In recursive schemes one always need to consider the case at which point recursion should stop. Recursion 
should not be allowed indefinitely (and in fact, you should avoid recursions of many levels, say possibly 500 levels deep because
in practice the stack size is limited and you actually create an entry on the call stack (to be described shortly) as you recurse. Exceeding
the limit results in a stack overflow error). Note that as recursion proceeds, the first and last character are being
taken off of the string before passing to a new \mono{isPalindrome()} invocation. Therefore, there must be a level 
at which the incoming string is either a single character or empty, depending on the number of characters in the
original string specified by the user. Also note that the ordering of the two conditions on line 29 is significant.
Because if we find that the border character pair doesn't match, we can already claim the string is not a palindrome
without having to test the string in the middle. I used the short-circuiting property of \mono{\&\&} to achieve this.
If you swap the two conditions, then recursion must always have to proceed to the deepest level and the test is only
carried out just before you exit from each level, which is just a waste of time. \\

Depending on the problem nature, recursion may be a better solution compared with an iterative approach. For example,
a program which searches through a directory structure (say, search for certain files on the hard disk) is nearly
always implemented by a recursive scheme because directory structure is hierarchical, or in other words, nested by 
its very nature. Because the number of nested levels is not known in advance, an iterative scheme is unlikely to
be appropriate. \\

Recursion generally requires nested subroutine invocation. How is this possible? Subroutine invocation is internally kept track of
by a series of stacks. A \term{stack} is a data structure. Think of a stack as a pile of books lying on your desk. 
Only two operations are allowed on a stack, either you place a book at the top of the stack, or you take away a book 
from the top of the stack. You are not allowed to insert into or remove from it any books in the middle. 
I will now briefly go into the process of subroutine invocation because certain concepts will be
revisited in later chapters. \\

The basic idea is that a \term{call stack} is maintained by your program. The top of the stack reflects your
current environment. When a subroutine is invoked, a new entry is created on top of the stack to represent the 
new environment. Each environment holds a copy of the lexical variables (those declared with \mono{my}, to be
introduced later on) that are specific to its environment. When the current subroutine terminates, so is the
environment and the entry is removed from the top of the call stack. The environment previously in effect is
reinstated. Therefore, every invocation is independently represented by the corresponding entry on the stack.
This is how subroutine invocations are handled in programming languages. Note that this mechanism does not impose
any restrictions to nested subroutine invocation. Nested subroutine invocation is just performed in exactly 
the same way as invocation of another subroutine. \\

\subsection{Creating Context-sensitive Subroutines}

As we have seen, several builtin functions are context-sensitive. That is, a function call exhibits 
different behaviours depending on the context around the function call. Subroutines may exhibit this
behaviour too, with the \mono{wantarray()} function.  \\

The \mono{wantarray()} function determines the context around a specific subroutine invocation. 
Consider the following example: \\

\head{EXAMPLE}{wantarray()}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/wantarray.pl}
\addvspace{\baselineskip}

In this example, \mono{search()} is a context-sensitive subroutine which exhibits two different behaviours,
depending on scalar or list context. On line 35, \mono{\$search1} introduces a scalar context to the rvalue.
Therefore, there is a scalar context around \mono{search()}. Whereas on line 38, there is a list context instead.
The \mono{wantarray()} function returns a true value in a list context, while \mono{undef} in a scalar context.
Many constructs in this example are introduced at a later time in this chapter. However, the idea is pretty 
simple. In a list context, the subroutine accepts a variable number of parameters which are searched for the
existence of the given substring. Strings with contain the given substring are returned as an array. On the
other hand, in a scalar context, the subroutine accepts two parameters (you may pass additional parameters,
but they are simply ignored) indicating the substring and the string being searched. The offset associated
with the first occurrence of the string is returned using the \mono{index()} function. I will not 
describe the \mono{index()} function in detail in this tutorial, because its uses can be substituted 
by regular expressions which I will cover in Chapter~\ref{chap:regex}. \\

I would like to take this opportunity to introduce to you another predefined variable \mono{\$"} which
appears on line 39. This is called the \term{list separator}. As illustrated in the example, 
substitution also applies to arrays in double-quoted strings. Therefore, you should escape all \mono{@}
characters in string literals so that they are not interpreted as array variable substitution. The
list separator is embedded in between list elements during array variable substitution of double-quoted
strings. \\

% =================================================================================================

\section{Packages}

When you split your code into multiple files, Perl provides a nice mechanism to ensure that variables in different 
parts of your program do not clash. The mechanism is to divide your program into different \term{namespaces}. The 
idea is very simple --- each namespace has a label which uniquely identifies the namespace and we prepend to variable 
names the label so that we can differentiate in case two variables in two namespaces happen to have the same name. 
C++ uses the notion of namespace, while in Perl terminology a namespace is called a \term{package} instead. \\

Any variables not explicitly contained in any packages belong to the \texttt{main} package. Therefore, all variables
we have been using in fact belong to the \texttt{main} package. By declaring additional packages we create shields 
so that variables in different packages would not interfere with each other. Packages are fundamental to object-oriented
programming because each object is intended to be a self-contained unit. \\

\subsection{Declaring a Package}

A package extends from the package declaration up to the end of the enclosing code block, the closing bracket of
\texttt{eval()} (see Chapter~\ref{chap:eval}) or the end-of-file, whichever comes first (see the 
\link{http://www.perldoc.com/perl5.8.0/pod/perlmod.html}{perlmod} manpage). To declare 
the start of a package, put \\

\texttt{\textbf{% 
package \textsl{package\_name};
}} \\

Usually package declarations are placed at the beginning of source files to ensure that all variables in the file
are protected. For example, \\

\begin{verbatimtab}[4]
#!/usr/bin/perl -w

package Apple;

# Package extends to the end of the file
\end{verbatimtab}

If a package declaration is placed inside a code block, the package extends to the end of the code block: \\

\begin{verbatimtab}[4]
#!/usr/bin/perl -w

# `main' package
{
	package Apple;

	# package 'Apple' extends to the end of the block
	$var = 3;
}
# `main' package
\end{verbatimtab}

To avoid any misconceptions that may arise as you read on, I would like to remind you that packages appearing
inside code blocks, such as in the example shown above, continue to exist after the block is closed. Always
bear in mind that packages are only intended to prevent inadvertent clashing of namespace. It has nothing
to do with scoping. In the above example, the variable \mono{\$Apple::var} still has the value of 3 after the
containing block terminates. This is not the case for \mono{my} or \mono{local} variables, though, which we will come to
shortly. \\

Note that a package may be declared within the extent of another package. As illustrated in the above example,
the `Apple' package is declared within the extent of the `main' package. Therefore, you can declare an `Orange'
package within the extent of the `Apple' package, and each package protects the variables within its respective
extent. By convention, the first letter of a package name is capitalized, except the `main' package. \\

\subsection{Package Variable Referencing}

If you omit the package name when referencing a variable, e.g. \texttt{\$somevar}, it refers to the variable 
inside the current package. This also applies to variables in the \texttt{main} package. Therefore, by not 
explicitly declaring any packages in previous chapters we have been referring to variables in the current package,
that is, the \texttt{main} package. \\

If you need to refer to a package not contained in the current package, you need to qualify the variable with the
package name prepended, with `\texttt{::}' as the package separator.
Therefore, to refer to a scalar variable \texttt{\$var} in the \texttt{apple} namespace you need to write 
\texttt{\$apple::var}. If the package name is empty but contains the package separator, e.g. \texttt{\$::var},
the \texttt{main} package is assumed. \\

Because you need to explicitly qualify a variable with the package name if you have to refer to it in another package,
you will not modify it inadvertently unless that is your intention. That is exactly how namespaces work. \\

There is also an old syntax of using a quote instead of double colon for referring to package variables, for example,
\mono{\$orange'var}. This syntax may be deprecated in future versions of Perl. However, because it will be interpolated
in double-quoted strings, you should beware of strings such as ``\mono{\$people's pen}''. You should disambiguate
by putting a pair of curly braces around the variable name, such as ``\mono{\$\{people\}'s pen}''. \\

\subsection{Package Variables and Symbol Tables}

%\textit{\small Note: Difficult material ahead. Understanding of this section is not compulsory for practical Perl 
%programming nowadays. You may wish to defer this section until you need it.} \\

Each package in Perl maintains its own \term{symbol table}. A symbol table keeps track of a list of symbols defined in
the current package and their memory locations at which they can be found. For non-lexical variables (that is, those not
declared with the \mono{my} modifier) Perl needs to keep track of them because they are not confined to any environments. 
You may access the symbol table of a package through a hash whose name is the name of the package, followed by two
colons. For example, the hash representing symbol table of the \mono{main} package is \mono{\%main::}. The keys of
the hash are the names of symbols defined in the package. The corresponding values is a scalar representing 
an internal data structure of Perl known as a \term{typeglob} which in turn holds the references to the actual symbols. \\

To help you understand it, consider the \mono{@INC} array that we described earlier in this chapter. This array is
one of the predefined variables in Perl that is automatically listed in the symbol table of the \mono{main} package.
Therefore, there exists a key `INC' in \mono{\%main::}, that is, \mono{\$main::\{'INC'\}}. The value is a typeglob
which holds a list of references of symbols with the name INC, that is, \mono{@INC} and \mono{\%INC}. The typeglob
is represented by \mono{*main::INC}. The typeglob has a number of slots, each of which stores the references of a
different type such as scalar, array, hash, anonymous subroutine, filehandle and typeglob (which is just a reference
to itself). If there isn't a symbol of one type, the corresponding slot is simply null. You can access the reference
of \mono{@INC} and \mono{\%INC} through the symbol table with a so-called \mono{*FOO\{THING\}} syntax. In this example, 
that are \mono{*main::INC\{ARRAY\}} and \mono{*main::INC\{HASH\}} respectively. \\

Typeglobs were mainly used for parameter passing in earlier versions of Perl when references were not yet in the 
Perl language. In the next chapter you will be taught on how to use pass-by-reference for parameter passing. 
You may wonder why I need to mention typeglobs at all if it is no longer actively used. First, in order for you to 
understand how \mono{local} or package variables work, you'll need to know what a symbol table is. And, because the entries
in a symbol table are represented by typeglobs, it is difficult for me not to mention typeglobs at all. \\

\subsection{Package Constructors with \mono{BEGIN \{\}}}

In each package you may define one or more subroutines with the name \mono{BEGIN}, which are automatically 
executed when the package is being parsed. During parsing, when perl sees these subroutines, they are
automatically executed in the order these subroutines are defined.
That means, these subroutines are executed before the rest of the program does. Customarily, the 
\mono{sub} keyword is omitted. \\

That being said, these subroutines
are not truly subroutines. After they have been executed, these subroutines are not registered in the 
symbol table. Therefore, you cannot manually invoke them during runtime. One of the major uses of
\mono{BEGIN} blocks is to modify \mono{@INC} to include additional module search paths, especially
because \mono{use} is a compile-time statement (modules are loaded during compile-time as opposed to runtime
--- see Chapter~\ref{chap:oop}). Therefore, you have to ensure that \mono{@INC} gets modified before
any \mono{use} statements: \\

\begin{verbatimtab}[4]
BEGIN {
	@INC = (@INC, './libs');
}

use MyLib;		# defined in ./libs
# ....
\end{verbatimtab}

\section{Lexical Binding and Dynamic Binding}

We have already learned how to define environments in a program by establishing code blocks in Section~\ref{sec:scope}.
Subroutine definition is also placed inside a code block so it also defines an environment in itself. However, I have
not yet explained how you can restrict an association to within a certain environment. Recall that all variables we have
been using are package variables. Once declared, package variables continue to exist in the symbol table as long as 
the program is running. Before we go into the details of the two types of bindings with respect to associations,
let us first examine the general concept of referencing first. \\

Let's execute this program on your system: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
for (keys %main::) {
    print $_, " => " , $main::{$_}, "\n";
}

$abc = 3;
\end{lstlisting}

The generated lines that are of interest at this point are shown below, with others omitted: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground},numbers=none]{}
...
stdin => *main::stdin
ARGV => *main::ARGV
INC => *main::INC
ENV => *main::ENV
abc => *main::abc
...
\end{lstlisting}
 
The above code dumps the content of the symbol table. On the left of the arrow are the names of the symbols,
while on the right are the corresponding typeglobs. What appears to be interesting is that an entry for \mono{abc}
exists in the symbol table, regardless of the fact that the statement which assigns 3 to \mono{\$abc} has not yet
been executed at the instant the symbol table dump is made. The reason is that a compilation step, despite invisible to users, was performed
before the actual execution which scans the whole program for package variables which are then added to the symbol
table. Therefore, before the program is actually executed the symbol table has already been constructed. As noted
previously, a symbol table keeps track of the symbols that appear in the program. By doing so, the runtime environment
(for example, the perl interpreter) prepares a list of symbols at an early point in time which facilitates it to
arrange for storage space in the memory and, most importantly, to prepare for referencing operations that occur
during execution of the program. \\

Whenever a symbol appears in a program, a referencing operation is required to be carried out during execution 
to deduce which data object is associated with the given symbol. For example, when the statement \mono{\$abc = 3;}
in the program above was executed, the runtime environment needs to find out which data object is associated with
the scalar variable \mono{\$abc}. The goal of a referencing operation is to locate this association. \\

Referencing has been made complicated because of the presence of scopes. Without scopes, referencing is easy because
there can be only one variable of a certain name in each package. For example, throughout the duration of a program there
can be one and only one scalar variable \mono{\$Apple::var} in the \mono{Apple} package. \mono{\$Orange::var} is 
already a different scalar variable and do not interfere with \mono{\$Apple::var} at all. Therefore, throughout 
the program all references to \mono{\$Apple::var} always refer to the same data object. However, this may not apply
to those variables which are confined by scoping rules. In Perl, two major types of scoping rules are supported, 
namely \term{lexical scoping} and \term{dynamic scoping}. Both scoping systems base on definition of environments such
as code blocks, but the way referencing is performed is different. \\

Most modern programming languages only support lexical scoping. An association that is lexically scoped is visible
from the point in the environment in which it is defined, and all environments that appear inside the extents of that environment, 
until when another lexically scoped variable with the same name appears in those environments.
In Perl, a variable declared with the \mono{my} modifier is lexically scoped. Consider this example: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
my $a = "Hello ";
{
	$a .= "World\n";
	print $a;		# Hello World
	my $a = "Bye!\n";
	print $a;		# Bye!
}
print $a;			# Hello World
\end{lstlisting}

When execution proceeds to line 3, Perl needs to find out which data object \mono{\$a} refers to. At this instant, 
the current environment, that is the code block between line 2 and 5, is known as the \term{local referencing environment}. 
Perl first finds out that up to this point there is not any lexical variable with the name \mono{a} in the local
referencing environment. As local referencing fails, the referencing operation proceeds to search for one in the
\term{nonlocal referencing environments}, by proceeding all the way up through parent environments. Here, we find 
a lexical \mono{\$a} in the parent environment, and the data object associated with that variable is used. Therefore,
the string ``World\textbackslash n'' is appended to the scalar value held by that data object. \\

However, on line 5 a new lexical \mono{\$a} is declared at this point. Therefore, referencing operation performed
at line 6 resolves to this lexical. Note that the lexical in the parent environment is untouched, but cannot be accessed
anymore in the current environment. It is described as being \term{hidden}.
When the code block terminates, all local associations are destroyed. Because of the reference-based garbage collection
mechanism, the data object associated with the lexical on line 5 is also destroyed. The parent environment that is
once invisible springs into existence again, and lexicals that were once hidden are
visible again. Therefore, the last \mono{print()} outputs ``Hello World''. \\

\texttt{my} expects a scalar or a list as its argument. We have seen a scalar used as the argument in the examples.
Using a list as an argument with optional assignment looks like this: \\

\begin{verbatimtab}[4]
my ($a, $b) = ('Hello', 'World');
\end{verbatimtab}

If the variable list is not assigned, then they are given the values of \texttt{undef}. \\

Lexical scoping models are recommended for several reasons. First, the use of lexical variables is faster compared 
with dynamically scoped ones. That is because lexical scoping can be solely determined from the nesting of code 
blocks, which is already fixed during the compilation phase. Therefore, referencing of lexical variables can be
performed during compilation instead of at runtime. Dynamic scoping, on the other hand, also takes into account the dynamic factor of subroutine invocations.
In Perl, \texttt{local} variables are dynamically scoped. As the use of dynamically scoped variables share similar problems
as global variables in other programming languages, and the scope is dependent on the call stack which is determined by how
the program calls subroutines at runtime, they make debugging more difficult, and are relatively slower. \\

\mono{my} variables are never listed in the symbol table. This fact is important as you go on and learn how to use
typeglobs. \\

Dynamic scoping, on the other hand, is based on the \term{call stack} instead of nesting of environments. In Perl,
\mono{local} variables are dynamically scoped. These variables are package variables and appear in the symbol table
of the respective packages. The idea is, when a \mono{local} variable is declared, the current value as can be accessed
through the symbol table is saved temporarily in a hidden stack, and a new data object is created to hold the new value.
When the current environment terminates, the current symbol table entry is removed, and the value that was previously 
saved is reinstated. Consider this example: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
sub greeting {
	print $a;		# Bye!
}

$a = "Hello ";
{
	$a .= "World\n";
	print $a;		# Hello World
	local $a = "Bye!\n";
	&greeting;
}
print $a;			# Hello World
\end{lstlisting}

This is similar to the example I used above to introduce \mono{my} variables in Perl, except now \mono{local} is
used and the second \mono{print} is put in a subroutine. On line 9, the original symbol table entry for \mono{\$a}
(with the scalar value ``Hello World'') is replaced with a newly created data object whose value is ``Bye!''. In
the subroutine \mono{greeting()}, because \mono{\$a} cannot be resolved in the local environment, the symbol table entry is used,
and therefore ``Bye!'' is displayed. When the block terminates, the original symbol table entry saved is reinstated.
Therefore, the value \mono{print}ed is ``Hello World''. \\

There are a few points to note here. Here is a slightly modified version of the above program for illustration: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
my $a = "Hello ";

sub greeting {
    print $a;			# Hello World!!!!
}

{
    $a .= "World\n";
    print $a;
    local $::a = "Bye!\n";
    &greeting;
}
print $a;
\end{lstlisting}

When you run this program, you would find that all three \mono{print()} result in the string ``Hello World'' being
displayed. The reason is that during compilation phase all references to \mono{\$a} within the lexical scope have
already been associated with the lexical variable. If you swap the positions of the lexical variable declaration and
the subroutine, you will find that the \mono{local}ized package variable \mono{\$a} is \mono{print}ed in this case. \\

Also, as shown on line 10, when you try to \mono{local}ize a variable when a lexical variable of the same name
exists, you have to explicitly use the double-colon form to indicate the package symbol table entry. That is 
because, as explained, \mono{\$a} is tied to the lexical variable and trying to \mono{local}ize a lexical variable 
is a runtime error. \\

Apart from a package variable, you can \mono{local}ize a member of composite type. For example, you can have \\ 

\begin{verbatim}
local $ENV{'PATH'} = '/home/cbkihong/bin';
\end{verbatim}

which causes the original value to be saved and temporarily replaced by the new given value. When the environment 
terminates the original value is restored. \\

Because of potential confusions that may arise when you use \mono{local} variables, one is generally not recommended
to use \mono{local} variables. \\

%\p{As previously noted, the concept of abstraction helps separate us from the computer hardware. In this way, we
%don't need to know how something actually works --- we are only interested in how to use it. Therefore, we can
%regard it as a \term{black-box}.}

%\p{In the following sections we will see what are subroutines and the two types of variables whose 
%scopes are restricted, by means of the \texttt{my} and \texttt{local} modifiers.}



% ====================================================================== 

%\section{Local Variables with \texttt{my}}

%\p{By default, all Perl variables are global. We can override this behaviour for individual variables (and hashes
%and arrays alike --- omitted thereafter for brevity) by applying the \texttt{my} \term{modifier}. Consider this
%example:}

%\head{EXAMPLE}{}%
%\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/eg0501.pl}

%\addvspace{\baselineskip}

%\p{This program should be executed with \texttt{\textbf{-w}} enabled. You should see 3 lines. This is the output
%on my machine:}

%\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
%Name "main::a" used only once: possible typo at eg0501.pl line 7.
%4
%Use of uninitialized value in concatenation (.) or string at eg0501.pl line 7.
%\end{lstlisting}

%\addvspace{\baselineskip}

% References: perlmod, PPL book, perlvar
% Global variables actually belong to "main" package; code generation and parse-build package-level symbol table 
% note that first warning message precedes print() --- actually output at compilation phase
% define-and-use. So usually at least two accesses to the variable.

% TODO: what about our?

%\p{Forget about line 1 of the output for the time being. This warning is actually generated during the compilation
%phase, before the actual execution of the script. Therefore, it appears before the other two lines which are 
%generated at runtime. Line 2 is the result of execution of line 5 in the source code. This fits our expectation
%that 4 has been assigned to \texttt{\$a} and the value is \texttt{print}ed. However, on line 3 the runtime warning
%message indicates \texttt{\$a} is not initialized. That is because the local variable \texttt{\$a} is destroyed
%when the block in which it resides terminates. As \texttt{\$a} is not initialized in the outer scope, its value
%is \texttt{undef}. That explains the warning message on line 3 when we want to \texttt{print} it in the outer
%scope.}

%\specialbox{NOTES}{%
%\p{My explanation above is not actually technically sufficient, although it should not be considered a fallacy.
%That is because there are some important concepts that I have not covered yet. In order to make my explanation
%easier and more understandable to you, I have tried to hide the complexities for a while. In fact, there are
%two important points that I will (and have to) clarify later on in the next chapter:}
%\begin{itemize}
%\item{Perl's global variables are not really global (because of the package mechanism);}
%\item{The \texttt{\$a} on line 5 and line 7 in Example 5.1 actually refer to two different variables under
%two different scoping mechanisms, namely \term{lexical scoping} and \term{dynamic scoping} respectively which 
%gives rise to the different behaviours of \texttt{my} and \texttt{local} variables. That truly 
%explains why the warning appears as the ``global'' \texttt{\$a} has not ever been assigned to in the first place!}
%\end{itemize}
%\p{Read on to see what I mean. In this chapter, we focus on facts --- and we leave explanations until the next chapter.}
%}

%\p{The scope of a \texttt{my} variable is not confined to the block in which it resides. In case of nested blocks,
%it is also visible in inner blocks, except when another \texttt{my} variable of the same name is declared
%in an inner block, in which case the outer \texttt{my} variable would be invisible inside that block. Therefore,
%in the following program:}

%\begin{verbatimtab}[4]
%my $a = "Hello ";
%{
%	$a .= "World\n";
%	print $a;
%}
%print $a;
%\end{verbatimtab}

%\p{As the inner block does not define another scalar variable \texttt{\$a}, the scope of the scalar variable \texttt{\$a} 
%from the outer block extends into the inner block. Note that the variable gets modified in the inner block, and when the 
%inner block terminates, the value \texttt{print}ed is still ``\texttt{Hello World}''.}

% ====================================================================== 

\section{Conditionals}

A programming language is practically not useful if the statements are only allowed to run from the very first 
line to the last. Therefore, in this section we are going to talk about loops and conditionals. \\

You have used the comparison and logical operators in the previous chapter. By using conditionals, you can 
specify a block of code to be executed if a particular condition (test) is satisfied. This is what conditionals 
exactly do. \\

The \texttt{if-elsif-else} structure is the most basic conditional structure. The general form is: \\

\texttt{%
\textbf{if (}EXPR1\textbf{)} BLOCK\_1 \\
\textsl{\textcolor{optionalargs}{[\textbf{elsif (}EXPR2\textbf{)} BLOCK\_2] ... \\
\ [\textbf{else} BLOCK\_n]}} \\
}

The parts in square brackets denote the optional parts. The \texttt{if-elsif-else} structure works as follows: 
if \texttt{EXPR1} evaluates to true, statements in \texttt{BLOCK\_1} are executed, and the remaining \texttt{elsif}
or \texttt{else} parts are bypassed. Otherwise, Perl jumps to the next \texttt{elsif} or \texttt{else} part, if any. \\

Perl goes to the \texttt{elsif} part if the previous condition is not met (i.e. false). If \texttt{EXPR2} evaluates 
to true, \texttt{BLOCK\_2} is executed and the remaining parts are bypassed. There can be as many \texttt{elsif} 
parts as you like, and Perl will test each condition successively until any test evaluates to true. The \texttt{else}
part is placed at last, handling the situation when all the previous tests failed. The \texttt{BLOCK\_n} will be 
executed in this situation. \\

Figure~\ref{fig:if} presents the flowchart showing the sequence of actions performed inside an \texttt{if-elsif-else} 
conditional structure. \\

\image{!hbt}{0.6\textwidth}{!}{images/if.eps}{If-elsif-else Flowchart}{fig:if}

The following is a simple program in which the user inputs a number, and the program deduces whether it is an even
number, odd number or zero. \\

\head{EXAMPLE}{}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/eg0503.pl}

This program has all the three parts, forming a complete \texttt{if-elsif-else} structure. Because $0$ is customarily 
considered neither odd nor even, we have taken this special case into consideration. First it tests if the number is 
odd by checking if the modulus (remainder) is $1$. If this is true, line 9 would be executed. Otherwise, it jumps to 
line 10 to test if the number is $0$. If this test fails again, we know for sure that it should be an even number. \\

Perl also has an \texttt{unless} conditional structure. The following example illustrates its use: \\

 
\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
#!/usr/bin/perl -w

print "Please enter your age > ";
chomp($in = <STDIN>);
unless ($in < 18) {
    print "You are an adult.\n";
} else {
   print "You are less than 18 years old.\n";
}
\end{lstlisting}
 

If you use \texttt{unless}, the sense of the test is reversed. Line 6 is executed if the expression evaluates to 
\texttt{false}. If the expression evaluates to \texttt{true}, Perl executes the \texttt{else} part. In fact, the 
\texttt{unless} structure is somehow redundant. However, Perl gives you the flexibility to do your job in alternative 
ways. That is an exemplification of the Perl motto \textit{``There Is More Than One To Do It''}. You can replace 
line 5 with

\begin{verbatim}
if (!($in < 18)) {
\end{verbatim}

... or even \\

\begin{verbatim}
if ($in >= 18) {
\end{verbatim}
 
to achieve the same effect. \\

\section{Loops}

Sometimes we would like to have a mechanism to execute a sequence of statements repeatedly for a specific number of times 
or under a particular condition. A loop is the answer. First, I will introduce the \texttt{for} loop. \\

\subsection{\texttt{for} loop}

The \texttt{for} loop is inherited from C/C++. The general syntax is \\

\texttt{
for (\textcolor{optionalargs}{[init-expr]}; \textcolor{optionalargs}{[cond-expr]}; \textcolor{optionalargs}{[loop-expr]}) BLOCK
} \\
 
First, the initial expression \texttt{init-expr} is executed. In this part usually a variable would be defined that acts as a counter to 
keep track of the number of times executed. Then the conditional expression \texttt{cond-expr} is evaluated. If the 
expression evaluates to anything other than \texttt{undef}, empty string (``'') or the numeric 0 (i.e. the three scalar 
values that are defined as \texttt{false}), the \texttt{BLOCK} is executed. After the \texttt{BLOCK} has been executed, 
the \texttt{loop-expr} is evaluated. Then, a new cycle starts, and the \texttt{cond-expr} is evaluated again until the 
\texttt{cond-expr} evaluates to false, then the loop terminates. \\

The process described above could best be visualized using a block diagram as shown in Figure~\ref{fig:for}. \\

\image{!hbt}{0.8\textwidth}{!}{images/forloop.eps}{for-loop Flowchart}{fig:for}

We would now write a script that prints a special pattern on the screen. It consists of two isosceles triangles pointing vertically towards 
each other. \\

\head{EXAMPLE}{Double Triangles}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/eg0504.pl}

In the example, lines 5-7 handles the case if the user enters a number out of the range (1..50). In particular, the 
\texttt{die()} operator on line 6 outputs the error message specified to the standard error (STDERR), which is the 
screen by default, and then terminate the program. \\

On lines 9-14 I used the \texttt{for} loop to print the asterisks line by line. The \texttt{\$i} variable stores 
the number of asterisks to be printed at each cycle, while \texttt{\$trend} keeps track of whether you decrease or 
increase the number of asterisks by 2 after each loop. Initially 0 is assigned to \texttt{\$trend}, so that the 
conditional operator decrements \texttt{\$i} by 2 after each loop. The upper triangle is completed when \texttt{\$i} 
takes the value of 1 or 2, depending on whether the user has entered an odd or even number. At this point I assign 1 
instead, so that in the next loop \texttt{\$i} is incremented by 2. This loop is repeated until when \texttt{\$i} is 
greater than the width of the base specified. In this case, the loop stops. \\

Note that although line 9 looks a bit complicated and strange, this is grammatically correct. The \texttt{init-expr} 
part consists of two expressions separated with a comma operator. As you have learned from the previous chapter, both 
expressions would be evaluated while returning the value of the last expression. However, this return value is actually 
ignored in this case. \\

\subsection{\texttt{while} loop}

A \texttt{for} loop is not the only type of loop structure available. Another form of the loop structure I would like 
to mention is the \texttt{while} loop. This structure is simpler compared with \texttt{for} loop, and the syntax of 
which is as follows: \\

\texttt{%
\textbf{while (}cond-expr\textbf{)} BLOCK
} \\

How does it work? First, \texttt{cond-expr} is evaluated. If it evaluates to true, \texttt{BLOCK} is executed. After 
that \texttt{cond-expr} is tested again, and the loop just goes on indefinitely until \texttt{cond-expr} evaluates to 
false. \\

\subsection{\texttt{foreach} loop}

Now I would introduce to you another loop structure that works closely with the list data structure. The general syntax 
of a \texttt{foreach} loop is as follows: \\

\texttt{%
\textbf{foreach} \textcolor{optionalargs}{[[\textbf{my}] \$loop\_var]} \textbf{(} list \textbf{)} BLOCK
} \\

In every cycle of 
a \texttt{foreach} loop, an element from the specified array or list (\texttt{list}) is retrieved and assigned to a temporary \texttt{local} 
variable \texttt{\$loop\_var}, and \texttt{BLOCK} is executed. Looping continues until all the elements in \texttt{list} 
have been enumerated. For example, if we would like to check if a particular element exists in an array, we can use a 
\texttt{foreach} loop and iteratively checks if the returned element matches the data we are looking for, as in the example 
below: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
#!/usr/bin/perl -w

$searchfor = "Schubert";
@composers = ("Mozart", "Tchaikovsky", "Beethoven", "Dvorak", "Bach",
              "Handel", "Haydn", "Brahms", "Schubert", "Chopin");
$prompt = "$searchfor is not found!\n";
foreach $name (@composers) {
    if ($name eq $searchfor) {
        $prompt = "$searchfor is found!\n";
        last;
    }
}
print $prompt;
\end{lstlisting}

As mentioned previously, we should have used a hash in the first place, but we use a loop to demonstrate the use of 
\texttt{foreach} loop anyway. In this example, each of the names in \texttt{@composers} is compared with ``Schubert'' in 
turn, the name we are looking for. The loop keeps on going unless the name specified is found in the list, or all the 
elements have been exhausted without resulting in a match. It is apparent that ``Schubert'' is in the array, so we 
must always obtain a positive result. \\

In each \texttt{foreach} cycle, an element from the specified list or array is assigned to the scalar variable specified. 
If the variable is omitted (note that \texttt{\$loop\_var} is an optional argument), it defaults to \texttt{\$\_}. This 
is a special variable that Perl, in general, assigns temporary data to if no scalar variable is specified in certain 
operations. This special variable is used quite often in later chapters, like regular expressions, to shorten the length 
of the script. However, in my opinion, although you are allowed to make your scripts shorter by omitting specifying certain 
variables in Perl, it may cause your script to look more cryptic than necessary. However, many Perl programmers use such 
shorthands, and you should know how to interpret them, and this is the reason why I cover this here. \\

The variable \texttt{\$loop\_var} is in the form of a \texttt{local} variable. However, you may want to restrict it to
be lexical scoped. In this case, put \texttt{my} after \texttt{foreach}, as shown in the syntax above. \\

Some Perl programmers are lazy to type 7 characters for \texttt{foreach} so you may use the shorthand \texttt{for} instead.
Perl can differentiate whether you use the \texttt{for} loop or \texttt{foreach} loop from the syntax. \\

Also notice line 10. The \texttt{last} statement is one of the \term{loop control statements}. A loop control statement 
controls the execution of the loop. In the next subsection we would explore the loop control statements available in Perl. \\

You may attach an optional \mono{continue} block after a loop block, such as \mono{while} or \mono{foreach}, which will be executed
before starting another iteration to evaluate the conditional expression. This is similar in purpose to \mono{loop-expr}
in the \mono{for} loop, except this is a block instead of an expression. This is handy if you have to preform a number
of operations before starting a new iteration that is otherwise clumsy or cannot be represented by an expression. Here
is the double triangle example earlier rewritten with a \mono{continue} block: \\

\head{EXAMPLE}{Double Triangles (with continue block)}%
\lstinputlisting[backgroundcolor=\color{CodeBackground}]{src/scope/dbltriangle_while.pl}

\subsection{Loop Control Statements}

Loop control statements can only be used inside loops to control the flow of execution. \\

The \texttt{next} statement causes the rest of the code block to be bypassed and starts the next loop iteration. 
If a \mono{continue} block is present, it is also executed before starting another iteration. \\

\begin{itemize}
\item For \texttt{for} loops, \texttt{loop-expr} is evaluated, and then \texttt{cond-expr} is evaluated; 
\item For \texttt{while} loops, \texttt{cond-expr} is evaluated; 
\item For \texttt{foreach} loops, the next element is taken from \texttt{list}.
\end{itemize}

The \texttt{last} statement causes the rest of the code block to be bypassed and the loop then terminates. Execution 
starts at the statement immediately following the \texttt{BLOCK}. Any \mono{continue} block is also bypassed. \\

\section{Leftovers}

% do {}
% modifier

Before we end this chapter, we will look at some miscellaneous issues which have not yet been covered. A \mono{do} 
block contains a sequence of statements which are sequentially executed, while returning the value resulting from the last statement. A
\mono{do} block is usually used with a modifier. Perl has defined a number of \term{modifiers} which can be attached
to the end of a statement. As an example: \\

\begin{verbatimtab}[4]
$i = 0;
do {
	print $i++, "\n";
} while ($i <= 30);
\end{verbatimtab}

which \mono{print}s all the integers from 0 up to 30. If a modifier is attached to a \mono{do} block, the block
is executed once before evaluating the condition. If the condition is true, then the block is executed again. Otherwise,
execution resumes on the next statement. The possible modifiers are: \\

\begin{verbatimtab}[4]
if EXPR
unless EXPR		# same as "if (!EXPR)"
while EXPR
until EXPR		# same as "while (!EXPR)"
foreach EXPR
\end{verbatimtab}

If a modifier is not attached to a \mono{do} block, as in the following example, the expression in the modifier
is evaluated before executing the rest of the statement: \\

\begin{verbatimtab}[4]
$i = 0;
print $i++, "\n" while ($i <= 30);	# prints 0 to 30
\end{verbatimtab}

This is actually equivalent to \\

\begin{verbatimtab}[4]
$i = 0;
while ($i <= 30) {
	print $i++, "\n";
}
\end{verbatimtab}


\begin{comment}		% XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
The \texttt{redo} statement causes the rest of the current code block to be bypassed and the block is re-executed. Conditional
expressions and loop expression (\texttt{for} loop) are not evaluated. The content of the loop variable is retained for 
\texttt{foreach} loops. This statement is seldomly used in practice. A clever use is to concatenate lines in a file with
line continuation characters. Some programming languages have the notion of \term{line continuation characters} which allow a
lengthy line to be split over multiple lines. Those languages usually do not have statement termination indicators (like \texttt{;}
in Perl) and generally use newlines to denote the end of a statement. In order to split a lengthy line over multiple lines, they
require a specific line continuation character before each intermediate line break that should not be considered the end of a statement.
In this way, all the lines terminating with a line continuation character are concatenated until a newline without any line continuation 
characters occur. For example, given the following input file: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground},numbers=none]{}
./configure --with-features=huge \
	--with-compiledby="Bernard Chan" \
	--enable-multibyte --enable-xim --enable-fontset \
	--enable-gui=gtk --with-gtk-prefix=/usr
\end{lstlisting}

\textit{(This is the configuration command before compilation of the GVIM editor on my Linux system)} \\

The following code snippet can be used to concatenate such lines into one: \\

\begin{lstlisting}[backgroundcolor=\color{CodeBackground}]{}
open FILE, "<command.txt";
while (defined($line = <FILE>)) {
    chomp($line);
    if ($line =~ s/\s*\\$//) {	# remove line continuation character if any
		# collapse multiple spaces into one
		($_ = <FILE>) =~ s/^\s*/ /;
        $line .= $_;
        redo unless eof(FILE);
    }
    # no more continuing lines --- process combined $line
	print $line;
}
close FILE;
\end{lstlisting}

This example is taken from the \link{http://www.perldoc.com/perl5.8.0/pod/perlsyn.html\#Loop-Control}{perlsyn} manpage with little
modification and comments added, because it uses certain Perl language features that have not been taught yet (like regular expressions).

\end{comment}	% XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

\section*{Summary}

\begin{summary}
\item The \mono{require()} function is used to source in external files.
\item The \mono{@INC} array stores path prefixes Perl uses to find an external source file.
\item An association exists between a variable name and the underlying data object.
\item The scope of an association refers to the region in which the association is visible.
\item Scopes are determined by nesting of environments. An environment is established inside a pair of curly braces.
\item A subroutine consists of a sequence of statements defining an environment, which may accept a list of scalars as parameters and return a list of values to the caller.
	\begin{summary}
	\item Subroutines enforce reusability of code snippets and make debugging easier.
	\item Parameters are merged into a single list and passed into a subroutine which may be retrieved from the array \mono{@\_}.
	\item A subroutine may return a scalar value or a list of values to the caller by using the \mono{return} function.
	\item Prototypes allow type checking of subroutine invocations at compile time.
	\item In a subroutine you may determine the context around the subroutine invocation by using the \mono{wantarray()} function. 
	\end{summary}
\item Recursion refers to the technique of tackling a problem by defining the solution in terms of itself. In programming languages this is achieved by nested subroutine invocation.
\item Package, or namespace, is a mechanism to minimize variable name clashes. 
	\begin{summary}
	\item Variables of the same name may exist concurrently in each package.
	\item Variables not within the extents of any packages belong to the \mono{main} package.
	\item Package variables are referenced by qualifying the variable name with the package name, followed by \mono{::}. 
		\begin{summary}
		\item Defaults to the \mono{main} package if \mono{::} is present but the package name is not specified.
		\item Defaults to the current package in effect if both the package name and \mono{::} are absent.
		\end{summary}
	\item Package variables are resolved from the symbol table.
	\item Each package may have multiple \mono{BEGIN} blocks which are executed at compile time.
	\end{summary}
\item An association that is lexically scoped is visible from the point in the environment where it is established and all environments that exist within the extents of the current environment, until the end of the current environment. \mono{my} variables are lexically scoped.
\item The scope of an association that is dynamically scoped depends on the call stack. A dynamically scoped association exists as long as the current environment is not destroyed. \mono{local} variables are dynamically scoped.
\end{summary}

\section*{Web Links}

\begin{list}{\thechapter.\arabic{count}}{\usecounter{count}}
\item {
	\link{http://perl.plover.com/FAQs/Namespaces.html}{Coping with Scoping} \\
	\textit{http://perl.plover.com/FAQs/Namespaces.html}
}
\end{list}

\section*{Questions}

\begin{enumerate}
\item In Example 3.7 I presented a binary search program to check if a user-specified integer exists in the list of 100 randomly-generated
integers. Introduce the following changes to the program: 

\begin{itemize}
\item convert it from iterative to recursive approach;
\item only the search routine is sufficient. You are not required to write the parts which accept user input and generate integers in random;
\item use lexical variables wherever appropriate;
\item the search routine should be placed inside a package with name \mono{Search}, in an external file ``binarysearch\_recursive.pl'';
\end{itemize}

There should be at least a \mono{binarySearch()} subroutine which is in the \mono{Search} package (namespace), which can be invoked as follows: \\
\begin{verbatim}
require 'binarysearch_recursive.pl';
my $exists = Search::binarySearch(@array, $integer);
\end{verbatim}
where \mono{@array} is any array containing a list of integers, \mono{\$integer} is the integer to search for, and \mono{\$exists} is 1 if the integer is found, \mono{undef} otherwise. \\

You may save the number of comparisons taken to reach a conclusion as a package variable \mono{\$numSteps} in the \mono{Search} package that can be accessed directly or through a subroutine. \\
\end{enumerate}
