
\documentclass[11pt]{article}

\setlength{\oddsidemargin}{0in}
\setlength{\evensidemargin}{0in}
\setlength{\topmargin}{0.0in}
\setlength{\headheight}{0in}
\setlength{\headsep}{0in}
\setlength{\textwidth}{6.5in}
\setlength{\textheight}{9.0in}
\setlength{\parindent}{0in}
\setlength{\parskip}{0.1in}

\usepackage{times}
\usepackage{url}

\begin{document}

\title{A Quick, Painless Introduction to the Perl Scripting Language}


\author{Norman Matloff\\
 University of California, Davis\\
        \copyright{}2002, 2003, N. Matloff}


\date{July 9, 2003}   

\maketitle
\tableofcontents{}

\newpage

\section{What Are Scripting Languages?}

Languages like C and C++ allow a programmer to write code at a very
detailed level which has good execution speed.  But in many applications
one would prefer to write at a higher level.  For example, for
text-manipulation applications, the basic unit in C/C++ is a character,
while for languages like Perl and Python the basic units are lines of
text and words within lines.  One can work with lines and words in
C/C++, but one must go to greater effort to accomplish the same thing.
C/C++ might give better speed, but if speed is not an issue, the
convenience of a scripting language is very attractive.

The term {\it scripting language} has never been formally defined, but
here are the typical characteristics:

\begin{itemize}

\item Used often for system administration and ``rapid prototyping.''

\item Very casual with regard to typing of variables, e.g. no
distinction between integer, floating-point or string variables.
Functions can return nonscalars, e.g. arrays, nonscalars can be used as
loop indexes, etc.

\item Lots of high-level operations intrinsic to the language, e.g.
stack push/pop.

\item Interpreted, rather than being compiled to the instruction set of
the host machine.

\end{itemize}

Today the most popular scripting language is probably Perl.  However,
many people, including me, strongly prefer Python, as it is much cleaner
and more elegant.

Our introduction here assumes knowledge of C/C++ programming.  There
will be a couple of places in which we describe things briefly in a UNIX
context, so some UNIX knowledge would be helpful.\footnote{But certainly
not required.  Again, Perl is used on Windows and Macintosh platforms
too, not just UNIX.}

\section{Goals of This Tutorial}

Perl is a very feature-rich language, which clearly cannot be discussed
in full detail here.  Instead, our goals here are to (a) enable the
reader to quickly become proficient at writing simple Perl programs and
(b) prepare the reader to consult full Perl books (or Perl tutorials on
the Web) for further details of whatever Perl constructs he/she needs
for a particular application.

Our approach here is different from that of most Perl books, or even
most Perl Web tutorials.  The usual approach is to painfully go over all
details from the beginning.  For example, the usual approach would be to
state all possible forms that a Perl literal can take on.  

We avoid this here.  Again, the aim is to enable the reader to quickly
acquire a Perl foundation.  He/she should then be able to delve directly
into some special topic, with little or not further learning of
foundations.

\section{A 1-Minute Introductory Example}

This program reads a text file and prints out the number of lines and
words in the file:

\begin{verbatim}
# comments begin with the sharp sign

# open the file whose name is given in the first argument on the command
# line, assigning to a file handle INFILE (it is customary to choose
# all-caps names for file handles in Perl) 
open(INFILE,@ARGV[0]);  

# names of scalar variables must begin with $
$line_count = 0;
$word_count = 0;

# <> construct means read one line; undefined response signals EOF
while ($line = <INFILE>) {
   $line_count++;
   # break $line into an array of tokens separated by " ", using split()
   # (array names must begin with @)
   @words_on_this_line = split(" ",$line);
   # scalar() gives the length of any array
   $word_count += scalar(@words_on_this_line);
}  

print "the file contains ",$line_count," lines and ",
   $word_count, " words\n";
\end{verbatim}

Note that as in C, statements in Perl end in semicolons, and blocks are
defined via braces.

\section{Variables}

\subsection{Types}

Type is not declared in Perl, but rather is inferred from a variable's
name (see below), and is only loosely adhered to.

Note that a possible value of a variable is undefined, which may
be tested for, using a call to {\bf defined()}. 

Here are the main types:

\begin{itemize}

\item Names of {\bf scalar} variables begin with \$.

Scalars are integers, floating-point numbers and strings.  For the most
part, no distinction is made between these.\footnote{There are various
exceptions, though.  

One class of exceptions involves tests of equality or inequality.  For
example, use ``eq'' to test equality of strings but use ``=='' for
numbers.}

\item Array names begin with @.  Indices are integers beginning at 0,
and the array elements are scalars (and thus array elements begin with
\$, not @).

Arrays are referenced for the most part as in C, but in a more flexible
manner.  Their lengths are not declared, and they grow or shrink
dynamically, without ``warning,'' i.e. the programmer does not ``ask for
permission'' in growing an array.  For example, if the array {\bf \@x}
currently has 7 elements, i.e. ends at {\bf \$x[6]}, then the statement 

\begin{verbatim}

$x[7] = 12;

\end{verbatim}

changes the array length to 8.

The programmer can treat an array as a queue data structure, using the
Perl operations {\bf push} and {\bf shift} (usage of the latter is
especially common in the Perl idiom), or treat it as a stack by using
{\bf push} and {\bf pop}.

An array without a name is called a {\bf list}.  For example, in

\begin{verbatim}

@x = (88,12,"abc");

\end{verbatim}

the right-hand side of the assignment statement is a list.  (We will
then have {\bf \$x[0]} = 88, etc.)

One of the big uses of lists and arrays is in loops,
e.g.:\footnote{C-style {\bf for} loops can be done too.}

\begin{verbatim}
# prints out 1, 2 and 4
for $i ((1,2,4))  {
   print $i, "\n";
}
\end{verbatim}

The length of an array or list is obtained calling {\bf scalar()},
or by simply using the array name in a scalar context.

\begin{verbatim}
$x[0] = 15;
$x[1] = 16;
$y = shift @x;
print $y, "\n";  # prints 15
print $x[0], "\n";  # prints 16
push(@x,9);  # sets $x[1] to 9
print scalar(@x), "\n";  # prints 2
print @x, "\n";  # prints 169 (16 and 9 with no space)
$k = @x;
print $k, "\n";  # prints 2
@x = ();  # @x will now be empty
print scalar(@x), "\n";  # prints 0
\end{verbatim}

\item As a first look, you can think of {\bf hashes} or {\bf associative
arrays} as arrays indexed by strings instead of by integers.  Their
names begin with \%, and their elements are indexed using braces, as in

\begin{verbatim}

$h{"abc"} = 12;
$h{"defg"} = "San Francisco";
print $h{"abc"}, "\n";  # prints 12
print $h{"defg"}, "\n";  # prints "San Francisco"

\end{verbatim}

However, a closer look at hashes reveals them to essentially be like
C {\bf struct}s.  In the above example, for instance, we have set up a
has named \%h which is analogous to a C {\bf struct} with {\bf int} and
{\bf char []} fields, whose values here are 12 and ``San Francisco'',
respectively.  This correspondence is more clear in the equivalent (and
more commonly used) code

\begin{verbatim}

%h = (abc => 12,
      defg => "San Francisco");
print $h{"abc"}, "\n";  # prints 12
print $h{"defg"}, "\n";  # prints "San Francisco"

\end{verbatim} 

Here the first two lines look rather the declaration of a C {\bf
struct}, as in

\begin{verbatim}

struct ht {
   int abc;
   char defg[20];
};

struct ht h;

h.abc = 12;
strcpy(h.defg,"San Francisco");

\end{verbatim}

Note, however, that there is no analog of ht in our Perl example above.
This will come, though, when we discuss object-oriented programming in
Perl below.

Moreover, unlike C {\bf struct}s, hashes actually store their field
names.  In the example above, the number 12 and the string ``San
Francisco'' are stored, but not the field names abc and defg.  By
contrast, Perl stores both!  In the code above, if we add the line

\begin{verbatim}

print %h, "\n";

\end{verbatim}

the output of that statement will be

\begin{verbatim}

abc12defgSan Francisco

\end{verbatim}

\item {\bf References} are like C pointers.  They are considered scalar
variables, and thus have names beginning with \$.  They are dereferenced
by prepending the symbol for the variable type, e.g. prepending a \$ for
a scalar, a @ for an array, etc.:

\begin{verbatim}
# set up a reference to a scalar
$r = \3;
# now print it, prepending an extra $ since it is a scalar
print $$r, "\n";  # prints 3

@x = (1,2,4,8,16);
$s = \@x;
# an array element is a scalar, so prepend a $
print $$s[3], "\n";  # prints 8
# for the whole array, prepend a @
print scalar(@$s), "\n";  # prints 5
\end{verbatim}

\end{itemize}

In Line 4, for example, you should view {\bf \$\$r} as {\bf \$(\$r)},
meaning take the reference {\bf \$r} and dereference it, the latter
being done by the dollar sign on the left.

\subsection{Anonymous Data}

{\bf Anonymous} data is somewhat analogous to data set up using {\bf malloc()}
in C.  One sets up a data structure without a name, and then points a
reference variable to it.

A major use of anonymous data is to set up object-oriented programming,
if you wish to use OOP.  (Covered in Section \ref{oop}.)

Anonymous arrays use brackets and braces instead of parentheses.  The
=> operator is used for dereferencing. 

Example:

\begin{verbatim}
# $x will be a reference to an anonymous array
$x = [5, 12, 13];
print $x->[1], "\n";  # prints 12 

# $y will be a reference to an anonymous hash (due to braces)
$y = {name => "penelope", age=>105};
print $y->{age}, "\n";  # prints 105
\end{verbatim}

\subsection{Declaration of Variables}

Variables in Perl are global by default.  To make a variable local to
subroutine or block,\footnote{This includes, for example, a block within
an {\bf if} statement.} the {\bf my} construct is used.\footnote{There
are many other scope possibilities, e.g. namespaces of packages.}  

A variable need not be explicitly declared; its ``declaration'' then
consists of its first usage.  For example, if the statements

\begin{verbatim}
$x = 5;  # $x is global
...
$my y = 12;  # $y is local
\end{verbatim}

were the first references to {\bf \$x} and {\bf \$y} in the code, then
this would both declare {\bf \$x} and {\bf \$y} and assign 5 and 12 to
them.

If you wish to make a separate declaration, you can do so, e.g.

\begin{verbatim}
$x;
...
$my y;
...
$x = 5;
$y = 12; 
\end{verbatim}

If you wish to have protection against accidentally using a variable
which has not be defined, say due to a misspelling, include a line

\begin{verbatim}
use strict;
\end{verbatim} 

at the top of your source code.

\section{Subroutines}

\subsection{Arguments, Return Values}

Arguments for a subroutine are passed via an array {\bf @\_}.  Note once
again that the @ sign tells us this is an array; we can almost think of
the array name as being {\bf \_}, with the @ sign then telling us it is
an array.  

Here are some examples:

\begin{verbatim}

# read in two numbers from the command line (note: the duality of
# numbers and strings in Perl means no need for atoi()!)
$x = @ARGV[0];
$y = @ARGV[1];
# call subroutine which finds the minimum and print the latter
$z = min($x,$y);
print $z, "\n";

sub min {
   if ($_[0] < $_[1]) {return $_[0];}
   else {return $_[1];}
}  

\end{verbatim} 

A common Perl idiom is to have a subroutine use {\bf shift} on @\_ to
get the arguments and asign them to local variables.

Arguments must be pass-by-value, but this small restriction is more than
compensated by the facts that (a) arguments can be references, and (b)
the return value can also be a list.

Here is an example illustrating all this:

\begin{verbatim}
$x = @ARGV[0];
$y = @ARGV[1];
($mn,$mx) = minmax($x,$y);
print $mn, " ", $mx, "\n";

sub minmax {
   $s = shift @_;  # get first argument
   $t = shift @_;  # get second argument
   if ($s < $t) {return ($s,$t);}  # return a list
   else {return ($t,$s);}
}
\end{verbatim}

Note carefully that all the arguments passed to a subroutine are strung
together as one long array.  For example,

\begin{verbatim}
$x[0] = 5;
$x[1] = 12;
$y[0] = 168;
$y[1] = 8888;
$z = f(@x,@y);
print $z,"\n";

sub f {
   $u = shift @_;
   $v = shift @_;
   return $u[0]+$v[1];
};
\end{verbatim}

will print out 5, not 8893.  The two 2-element arrays passed to {\bf f()}
will be considered as one 4-element array, of which {\bf \$u} will be
assigned the first of the four, i.e. 5, and {\bf \$v} will be assigned the
second, i.e. 12.  The Perl interpreter will then consider {\bf \$v[1]}
to be undefined, as there is no \underline{array} {\bf \@v}.

To get the desired effect, change everything to references:

\begin{verbatim}
$x[0] = 5;
$x[1] = 12;
$y[0] = 168;
$y[1] = 8888;
$z = f(\@x,\@y);  # pass references
print $z,"\n";

sub f {
   $u = shift @_;  # $u now points to @x
   $v = shift @_;  # $v now points to @y
   return $$u[0]+$$v[1];  # dereference
};
\end{verbatim}

\subsection{Alternative Notation}
\label{altnot}

Instead of enclosing arguments within parentheses, as in C, one can
simply write them in ``command-line arguments'' fashion.  For example,
the call

\begin{verbatim}

($mn,$mx) = minmax($x,$y);

\end{verbatim}

can be written as

\begin{verbatim}
($mn,$mx) = minmax $x,$y;
\end{verbatim}

In fact, we've been doing this in all our previous examples, in our
calls to {\bf print()}.  This style is often clearer.

On the other hand, if the subroutine, say x(), has no arguments make sure
to use the parentheses in your call:

\begin{verbatim}
x();
\end{verbatim}

rather than

\begin{verbatim}
x;
\end{verbatim}

In the latter case, the Perl interpreter will treat this as the
``declaration'' of a variable {\bf x}, not a call to {\bf x()}.

\subsection{Passing Subroutines As Arguments}

(This section may be skipped.  It is included here because I've found
the books often don't explain it clearly.)

Older versions of Perl required that subroutines be referenced through
an ampersand preceding the name, e.g.

\begin{verbatim}
($mn,$mx) = &minmax $x,$y;
\end{verbatim}

In some cases we must still do so, such as when we need to pass a
subroutine name to a subroutine.  The reason this need arises is that we
may write a packaged program which calls a user-written subroutine.

Here is an example of how to do it:

\begin{verbatim}

sub x  {
   print "this is x\n";
}
            
sub y  {
   print "this is y\n";
}
            
sub w {
   $r = shift;
   &$r();
}
            
w \&x;  # prints "this is x"
w \&y;  # prints "this is y"


\end{verbatim}

\section{Confusing Defaults}

In many cases, Perl the operands for operators have defaults if they are
not explicitly specified.  Within a subroutine, for example, the array
of arguments @\_, can be left implicit.  The code

\begin{verbatim}

sub uuu {
   $a = shift;  # get first argument
   ...
}

\end{verbatim}

will have the same effect as

\begin{verbatim}

sub uuu {
   $a = shift @_;  # get first argument
   ...
}

\end{verbatim}

This is handy for experienced Perl programmers but arguably a source of
confusion for beginners.

Similarly,

\begin{verbatim}

$l = <>;

\end{verbatim}

reads a line from the standard input (i.e. keyboard), just as the more
explicit

\begin{verbatim}

$l = <STDIN>;

\end{verbatim}

would.

\section{String Manipulation in Perl}

Perl contains an extremely rich set of string operations.  We will only
be able to just scratch the surface here.

One major category of Perl string constructs involves searching and
possibly replacing strings.  For example, the following program acts
like the UNIX {\bf grep} command, reporting all lines found in a given
file which contain a given string (the file name and the string are
given on the command line):

\begin{verbatim}

open(INFILE,@ARGV[0]);
while ($line = <INFILE>) {
   if ($line =~ /@ARGV[1]/)  {
      print $line;
   }
}
\end{verbatim}

Here the Perl expression

\begin{verbatim}
   ($line =~ /@ARGV[1]/)  
\end{verbatim}

checks \$line for the given string, resulting in a {\bf true} value if
the string is found.

In this string-matching operation Perl allows many different types of
{\bf regular expression} conditions.\footnote{If you are a UNIX user, you may be
used to this notion already.}  For example,

\begin{verbatim}
open(INFILE,@ARGV[0]);
while ($line = <INFILE>) {
   if ($line =~ /us[ei]/)  {
      print $line;
   }
}
\end{verbatim}

would print out all the lines in the file which contain {\it either} the
string ``use'' {\it or} ``usi''.

Substitution is another common operation.  For example, the code 

\begin{verbatim}
open(INFILE,@ARGV[0]);
while ($line = <INFILE>) {
   if ($line =~ s/abc/xyz/)  {
      print $line;
   }
}
\end{verbatim}

would cull out all lines in the file which contain the string ``abc'',
replace the first instance of that string in the line by ``xyz'', and
then print out those changed lines.

\section{Perl Packages/Modules}
\label{packmod}

Object-oriented programming (OOP, see Section \ref{oop}) came late to
Perl, as an add-on, so it's likely that most of the Perl programs being
used in the world do not make use of OOP.  However, you are likely to
encounter it anyway, in the form of modules which you will call from
your own code, even though the latter may not be OOP in nature.

For example, if you do network programming (see Section \ref{net}), you
will probably need to include a line

\begin{verbatim}

use IO::Socket;

\end{verbatim} 

in your code.

This means that you there will be a directory {\bf IO} in your Perl
search path,\footnote{There is a default path set up for Perl execution,
and you can supplement it by using the {\tt -I} option when you invoke Perl
from the command line.}, and that there is either a file {\bf Socket.pm}
in that directory which contains code you will call from your code, or
that {\bf Socket} is a subdirectory of IOIO and you will be calling code
from files within {\bf IO/Socket} whose suffixes are {\bf
.pm}.\footnote{If you know Java, you may notice that this is similar to
the setup for Java packages.}  In this case, it will be the latter
situation; for example, on my Linux machine, the directory {\bf
/usr/lib/perl5/5.6.0/IO/Socket} contains the files {\bf INET.pm} and
{\bf UNIX.pm}, and the socket code is in those files.\footnote{The
directory {\bf /usr/lib/perl5/5.6.0/} is in the default Perl search
path.}

Each package is typically in a separate file.  The {\bf package} keyword
begins the file.  For use as a module, the file name should begin with a
capital letter.

Any package which contains subroutines must return a value.  Typically
one just includes a line

\begin{verbatim}
1;
\end{verbatim}

at the very end, which produces a dummy return value of 1.

There are many public-domain Perl modules available in CPAN, the
Comprehensive Perl Archive Network, which is available at several sites
on the Web.  Moreover, the process of downloading and installing them
has been automated!

For example, suppose you wish to write (or even just run) Perl programs
with Tk-based GUIs.  If the Perl Tk module is not already on your
machine, just type

\begin{verbatim}

perl -MCPAN -e "install Tk"

\end{verbatim}

You will be asked some questions, but just taking the defaults will
probably be enough.

\section{OOP in Perl}
\label{oop}

(This section requires some knowledge of OOP, e.g. from C++ or Java.
The section may be skipped without compromising understanding of the
remaining material.  For a quick but rather thorough introduction to
Java, see \url{http://heather.cs.ucdavis.edu/~matloff/JavaIntro.pdf}.)

\subsection{General Mechanisms}

Though object-oriented programming capability came to Perl as a belated
add-on, it is done in a fairly simple and easy-to-use (if not elegant)
manner.  Here is an introduction, with some simple code for a warehouse
inventory program.

\subsection{Overview}

The following overview should be read both before and after reading the
example below in \ref{oopexample}, as it won't be fully clear until
after the reader sees an example.

A Perl class consists of a package file which contains various subroutines
({\bf methods}, in OOP terminology), one of which will serve as the
constructor.  

Unlike other OOP languages, in Perl we actually name the constructor
method ourselves.\footnote{And thus we can give it any name we choose.
In fact, even what appears to be something like C++'s and Java's {\bf
new} construct is little more than the name some authors of Perl modules
give to their constructors.} This code typically consists of:

\begin{itemize}

\item We set up an anonymous hash.

\item We point a reference variable to it.

\item We perform a {\bf bless} operation, which associates the
reference variable with the class name, so that the Perl interpreter
will know that this reference variable applies to member variable and
functions of that class.

\end{itemize}

The ``bless'' operation returns the reference, which then serves as a
pointer to the object.

Perl does not explicitly distinguish between class and instance
variables.\footnote{In OOP, a class will have some variables in common
to all objects of the class, called {\bf class variables}, and other
variables which have different values in each object, called {\bf
instance variables.}  If you have worked only in C++, you may not have
heard these terms, but they correspond to {\bf static} and non-{\bf
static} variables, respectively.}  Instead, they are distinguished by
context:

\begin{itemize}

\item The fields of the hash set up by the constructor will serve as the
instance variables of that object.  

\item Any variables declared in the package itself (i.e. not the
variables in the hash) will be the class variables.

\end{itemize}

Similarly, class and instance methods are not distinguished in any
formal way.  The methods, being subroutines, have an argument vector
{\bf @\_}, but the difference will be that the first argument: 

\begin{itemize}

\item {\bf \$@\_[0]}, will point to the class if the method is invoked
on the class

\item {\bf \$@\_[0]}, will point to the object if the method is invoked
on the object

\end{itemize}

For example, say we have a reference {\bf \$r} which points to an object
of class {\bf X}, and the class contains a subroutine {\bf s()} with a
single integer argument, then 

\begin{verbatim}
X->s(12);
\end{verbatim}

would set {\bf @\_} to consist of a pointer to {\bf X} and the number
12, while

\begin{verbatim}
$r->s(12);
\end{verbatim}

would set {\bf @\_} to consist of a pointer to the object (i.e. it would
be {\bf \$r}) and the number 12.  Thus {\bf s()} would serve as either a
class method or an instance method, according to context.

\subsection{Example}
\label{oopexample}

First we have the file {\bf Worker.pm}:

\begin{verbatim}
package Worker;

$lastupdate;  # a class variable

# this will be the constructor
sub newworker {
   my $classname = shift;  # class name (Worker) is first argument
   my ($nm,$id) = @_;  # get the other arguments
   # set up an anonymous hash and point a reference to it
   my $r = {name => $nm, id => $id};
   # set the time
   $lastupdate = localtime();
   # associate the reference with this class, and return the reference
   bless($r,$classname);
   return $r;
}

# a print routine; an instance method
sub printworker {
   my $r = shift;  # object is first argument
   print "employee number ",  $r->{id}, " is named ", $r->{name}, "\n";
}

# query time of last update; a class method
sub whenlast {
   print "database last updated ",$lastupdate, "\n";
}

1;  # a quirk in Perl; must include dummy return value as last line

# note:  we have no provision here for connecting the workers into one
# set, but we could have a class variable which is the head of a linked
# list, and have newworker add the new object to that list
\end{verbatim}

Here is a file which uses the {\bf Worker} package, say {\bf emps.pl}:

\begin{verbatim}
use Worker;  # like C's include

# add two workers
$w1 = Worker->newworker("Cassius",12);
$w2 = Worker->newworker("Penelope",5);

# print the workers 
$w1->printworker;
$w2->printworker;

# can access the objects from outside the class
print $$w1{name}, "\n";  # prints "Cassius"

# check how recent the data is
Worker->whenlast();
\end{verbatim}

One would type

\begin{verbatim}
perl emps.pl
\end{verbatim}

and the output would be something like

\begin{verbatim}
employee number 12  is named Cassius
employee number 5  is named Penelope
database last updated Sat Mar 16 20:30:29 2002
\end{verbatim}

\subsection{The Tie Operation}

Perl's {\bf tie} operation\footnote{Actually it is a Perl built-in
function, {\bf tie()}.} is an advanced topic.  Again, this section may
be skipped without loss of continuity.

What tie() does is a form of operator overloading.  It will associate a
scalar variable\footnote{Or an array or a hash.} with a class object.
That class is required to have subroutines named TIESCALAR, FETCH and
STORE:  TIESCALAR is the constructor function, and FETCH and STORE are
called each time the scalar needs to be fetched (e.g. is on the
right-hand side of an assignment statement) or stored (e.g. is on the
left side).  The methods in the class then allow one to intervene in the
fetch or store.

For example, suppose we have an integer variable whose value should not
go outside a certain range.  We can use tie() to do runtime checks for
exceeding that range.  We first set up the class, say BoundedInt.pm:

\begin{verbatim}
# use of tie() to implement bounds checking on integer variables

# arguments to tie() are the class name, BoundedInt, the name of
# the tied variable, and the lower and upper bounds

package BoundedInt;

sub TIESCALAR {
   my $class = @_[0];
   my $r = {Name=>@_[1], Value=>0, LBd=>@_[2],UBd=>@_[3]};
   bless $r, $class;
   return $r;
}

sub FETCH {
   my $r = shift;
   return $r->{Value};
}

sub STORE {
   my $r = shift;
   my $tryvalue = shift;
   if ($tryvalue < $r->{LBd} || $tryvalue > $r->{UBd})  {
      print "out-of-bounds value for ",$r->{Name},":  ",$r->{Value}, "\n";
   }
   else  {
      $r->{Value} = $tryvalue;
   }

}

1;  
\end{verbatim}

Now, here is a test program:

\begin{verbatim}
use BoundedInt;

package main;

$x;

tie $x,'BoundedInt','$x',1,10;
$x = 5;  # OK
$x = 15;  # causes an error message
$x = 3;  # OK

exit;
\end{verbatim}

As seen above, the first two arguments to {\bf tie()} must be the variable,
then the class name.  Further arguments depend on the application.

\section{Networking in Perl}
\label{net}

(This section requires an elementary knowledge of TCP/IP programming.
The section may be skipped without compromising understanding of the
remaining material.  For a quick but rather thorough introduction to
networks and TCP/IP, see
\url{http://heather.cs.ucdavis.edu/~matloff/Networks/Intro/NetIntro.pdf}.)

Perl includes analogs of most of the TCP/IP calls one is accustomed
to using from C, including {\bf select()}.  The arguments to the calls are
similar, though Perl, being at a higher level than C, makes many of
these calls more convenient.

Here is an example of code which a client may use to connect to a
server:

\begin{verbatim}

use IO::Socket;

# get server and port from command line
my $srvrip  = $ARGV[0];  
my $port = $ARGV[1];
my $svrskt = new IO::Socket::INET(PeerAddr=>$srvrip,
                             PeerPort=>$port, Proto=>'tcp');

\end{verbatim}

Nothing more need be done.  The call to {\bf new()} incorporates what in
C would be calls to {\bf socket()}, {\bf connect()} and so on.  

Assume that the data is line-oriented.  Then the client would send a
string {\bf \$x} (which, say, did not already have an end-of-line character)
as

\begin{verbatim}
$x = $x . "\n";  # . is Perl's string-concatenate operator
print $svrskt $x;
\end{verbatim}

and would read a line, say {\bf \$y}, as

\begin{verbatim}
$y = <$svrskt>;
\end{verbatim}

The server would have code something like

\begin{verbatim}
$port = $ARGV[0];  
$listensocket = IO::Socket::INET->new(Proto=>'tcp', LocalPort=>$port,
      Listen=>1, Reuse=>1);
...
$sock = $listensocket->accept();
$z = <$sock>;
...
print $sock $w, "\n";
\end{verbatim}

\section{Debugging in Perl}

(Before reading this section, if you are not a veteran debugger you may
wish to view the author's debugging slide show, at
\url{http://heather.cs.ucdavis.edu/~matloff/debug.html}.)

\subsection{Perl's Own Built-in Debugger}

Perl has its own reasonably-good debugging tool built right in to the
interpreter.  One merely runs Perl with the {\bf -d} option on the command
line, e.g.

\begin{verbatim}
perl -d x.pl
\end{verbatim}

Here are some of the debugger operations:

\begin{verbatim}
b k        set a breakpoint at line/subroutine k
b k c      set a breakpoint at line/subroutine k, with boolean condition c
n          go to next line, skipping over subroutine calls
s          go to next line, not skipping over subroutine calls
c          continue until breakpoint
c k        continue until line k/subroutine (one-time breakpoint)
L          list all breakpoints/actions
d k        delete breakpoint at line k
a k c      execute Perl command ("action") c each time hit breakpoint at k
a k        delete action at line k
r          finish this subroutine without single-stepping
p y        print y
x y        examine y (nicer printing of y)
T          stack trace
l          list a few lines of source code
!          re-do last command
H          list all recent commands
!n         re-do command n
h          help
|c         do debugger command c, but run output through pager
R          attempt a restart, retaining breakpoints etc.
q          quit
\end{verbatim}

Note that the {\bf p} command, applied to an array or hash, strings
together the elements; try using {\bf x} instead.  For example:

\begin{verbatim}
main::(u.pl:2): @u = (1,2,3);
  DB<1> n
main::(u.pl:3): %v = ("abc" => 12, 8 => 3);
  DB<1> n
main::(u.pl:4): $z = 0;
  DB<1> p @u
123
  DB<2> p %v
83abc12
  DB<3> x @u
0  1
1  2
2  3
  DB<4> x %v
0  8
1  3
2  'abc'
3  12
\end{verbatim}

The {\bf a} command is very useful.  E.g.

\begin{verbatim}
a 54 print "$x, $y\n"
\end{verbatim}

would result in printing out {\bf \$x} and {\bf \$y} every time you hit
the breakpoint at line 54.

\subsection{GUI Debuggers}

The built-in Perl debugger is certainly quite serviceable, but of course
it is nicer to have a GUI through which to use the built-in debugger.
Several debuggers provide this.

If you are on a UNIX system, I recommend DDD.\footnote{See the above
debugging Web page URL for information.}  By using DDD, one has the same
GUI no matter whether one is debugging C/C++, Java, Perl or Python.

A GUI debugger for Perl which can be used on any platform (since it
itself is written in Perl) is {\bf ptkdb}, which is available on CPAN.

\section{To Learn More}

There are obviously a great many good books on Perl.  One which I like
is {\it Perl by Example} (third edition), by Ellen Quigley.

There also are many books which treat various specialized aspects of
Perl, such as Perl network programming, Perl/Tk GUI programming and so
on.

There are a number of Perl Web pages, the ``official'' one being
\url{http://www.perl.com/}.

If you are on a UNIX system, type

\begin{verbatim}
man perl
\end{verbatim}

which will lead you to other man pages.  For example, 

\begin{verbatim}
man perlfunc
\end{verbatim}

will give you the documentation for all of Perl's built-in functions.

CPAN, an archive of many contributed Perl modules, was discussed
earlier, in Section \ref{packmod}.

\end{document}

