untitled

(ff) #1

10.1 Text Transformations 223


}

my $mean = $sum / $count;
my $var = ($sumsq - $count * $mean ** 2)
/ ($count - 1);
return ($mean, $var);
}


This procedure introduces some new notation. The most noticeable change
from the previous Perl programs is the use ofmyat the beginning of most
lines. The variables that have been used so far are known asglobalvariables.
They are accessible everywhere in the program. In particular, they can be
used in any of the procedures. The@tablevariable, for example, is used
in the first line of this procedure. Amyvariable, on the other hand, belongs
only to that part of the program in which it was declared. All but one of the
myvariables in this procedure belong to the procedure. The two exceptions
are$iand$field. Both of these belong to theforstatement. It is not
necessary to declare that such variables aremyvariables, but it is okay to do
so.
The advantage ofmyvariables is that they prevent any confusion in case
the same variable name is used in more than one procedure. While one can
certainly use ordinary global variables for computation done in procedures,
it is risky. To be safe, it is best for all variables that are only used within a
procedure to bemyvariables.
Thestatsprocedure is invoked by specifying the position of the field that
is to be computed. For example,stats(4)computes the mean and variance
of the column with index 4. This is actually the fifth column because Perl
array indexes start at 0. The number 4 instats(4)is called aparameterof
the procedure. The parameters given to a procedure are available within the
procedure as the@array. In particular, the first parameter is$[0],and
this explains the second line of the procedure:


my $column = $_[0];

which sets$columnto the first parameter given to the procedure when it is
invoked.
Thereturnstatement has two purposes. It tells Perl that the procedure
is finished with its computation. In addition, it specifies the end result of
the computation. This is what the program that invoked the procedure will
receive. Note that a list of two values is produced by this procedure. One can

Free download pdf