212 10 Transforming with Traditional Programming Languages
1/15/2000 18.66 normal 62 cm 46.27 kg 102 lb
1/15/2000 26.93 overweight 63 cm 68.95 kg 152 lb
2/1/2000 33.95 obese 65 cm 92.53 kg 204 lb
2/1/2000 17.38 normal 67 cm 50.35 kg 111 lb
The first step is to remove any extra space at the beginning and end of the
line. This is done with thechompfunction. This was not necessary in previ-
ous programs because the fields were in fixed locations in the line. It is a good
idea to usechompwhenever the input has variable-length fields. The next
step is to split the record into fields using thesplitoperator. This produces
the@recordarray. The values in this array are denoted by$record[0],
$record[1], $record[2],...The number in brackets is called thein-
dexorpositionof the value in the array. If one uses a negative index, then it
specifies a position starting from the last value (i.e., starting from the other
end of the array). Notice that the array as a whole uses@but the individual
values use$. Remember that in Perl, the initial character on a variable (and
there are more than just$and@) denotes the kind of value. It is not part of
the name of the variable.
The next step is to split the first field (i.e., the date) into its parts. The parts
are separated by slashes. The rest of the program is the same as the first
program except that array values are used instead of substrings. Another
difference is that the conditional statements are written with the if-conditions
first rather than after the statement. The first condition is indicated byif.
Subsequent conditions (except the last one) are indicated usingelsifwhich
is short for “else if”. The last case is indicated byelsewhich is used for
those cases not handled any other case. Putting the conditional after the
statement as in the first program is best if you think of the statement as being
subject to a condition. Putting a conditional before the statement is best if
you are thinking in terms of a series of cases, such that only one of them
applies to each record.
The split statement
@record = split(" ", $_);
could have been abbreviated to
@record = split(" ");
The default for splitting is to split up the value of$_. One can even abbrevi-
ate further to