untitled

(ff) #1

222 10 Transforming with Traditional Programming Languages



  • Brackets enclosing an array variable or braces enclosing a hash variable
    are used to refer to the array or hash as a single unit rather than as a
    collection of items.


•Theforstatement is used to perform some action for each number in a
sequence.

10.1.3 Perl Procedures


While the programs above are very good for accomplishing their tasks, it
should be clear that they would get rather tedious if one were computing
statistics for more than a couple of fields. A real health study database will
have hundreds of fields, and one would like to perform a large number of
statistical computations. So some other way to deal with the transformations
will be needed. In the case of statistics, the same kind of computation is
required over and over again. Rather than program this same computation
endlessly, one should just program it once, and then use that same program
whenever it is needed.
In Perl, a collection of statements that can be performed as a unit is called
aprocedure. They are also calledsubroutinesorfunctions. Performing a proce-
dure is calledinvocation. One also says that the procedure is beingexecutedor
called. One invokes a procedure by using the name of the procedure and a list
ofparameters. Procedures have already been used in the programs presented
so far. For example,splitis a procedure that splits apart a string into an
array of fields.
Returning to the health study, suppose that one would like to compute the
mean and variance for many of the fields. The computation for each field
is the same, so it is convenient to program it just once. Assuming that the
database is in a table (2D array) as in program 10.7, it is easy to use this table
to compute statistics with the following procedure namedstats:

sub stats {
my $count = @table;
my $column = $_[0];
my $sum = 0;
my $sumsq = 0;
for ($i = 0; $i < $count; $i++) {
my $field = $table[$i][$column];
$sum += $field;
$sumsq += $field * $field;
Free download pdf