untitled

(ff) #1

10.1 Text Transformations 221


print "Health Study Statistics\n\n";


while (<>) {
chomp;
push(@table, [split]);
$bmi = $record[1];
}


$count = @table;
for ($i = 0; $i < $count; $i++) {
$bmisum = $bmisum + $table[$i][1];
$bmisumsq = $bmisumsq + $table[$i][1] ** 2;
}


print("Number of records: $count\n");
$bmimean = $bmisum / $count;
print("Average BMI: $bmimean\n");
$bmivar = ($bmisumsq - $count * $bmimean 2)
/ ($count - 1);
print("BMI Variance: $bmivar\n");
$bmisd = $bmivar
0.5;
print("BMI Standard Deviation: $bmisd\n");


Program 10.7 Computing statistics using a 2D array

This way of specifying sequences is very common. It is used in all of the
major programming languages, including C++ and Java.
The expression$table[$i][1]gets the second field of one record from
the table. This is how one obtains one item in a 2D array in Perl (and, for that
matter, also in C++ and Java). In the language of matrices, the first index is
the row and the second index is the column.


Summary



  • An array of arrays is a two-dimensional array, also called a table. One can
    construct arrays having any number of dimensions.

  • Brackets are used for selecting one item from an array.

  • Braces are used for selecting the value associated with a key in a hash.

Free download pdf