210 10 Transforming with Traditional Programming Languages
program, and modified for each record in the health study file. The mean,
variance, and standard deviation are computed from these three values by
well-known formulas.
It is not actually necessary to initialize the three variables to 0. In other
words these three lines in the first part of the program could have been omit-
ted:
$count = 0;
$bmisum = 0;
$bmisumsq = 0;
Perl will automatically set any variable to a standard default value the first
time it is used. For numbers the default initial value is 0. For strings it is the
empty string.
Many commonly occurring statements can be abbreviated. For example,
the statement
$bmisum = $bmisum + $bmi;
can be abbreviated to the more succinct statement
$bmisum += $bmi;
Similar abbreviations are available for all the arithmetic operations such as
subtraction, multiplication, and division, as well as for other kinds of opera-
tion. Incrementing a variable (i.e., increasing it by 1) is so common that it has
its own special operator. As a result, one can abbreviate
$count = $count + 1;
to the more succinct
$count++;
So far the transformation tasks have been on data files in a fixed-width
format. The transformed data have used fields that vary in length. The next
task is to transform a data file with variable-length fields separated from one
another by spaces. This requires a new kind of variable as well as operations
for them. Anarrayorlistis a sequence of values. Perl indicates an array
variable with an initial@character. To transform a data file it must first be
splitinto fields. The result of the splitting operation is an array.