untitled

(ff) #1

216 10 Transforming with Traditional Programming Languages


Number of records: 2
Average BMI: 25.665
BMI Variance: 137.28245
BMI Standard Deviation: 11.7167593642611

As usual, there are many ways to abbreviate statements in this program.
One common abbreviation is to omit some of the parentheses in the foreach
statement. Thus

foreach $m (sort(keys(%count))) {

can be written

foreach $m (sort keys %count) {

One could also abbreviate it to

foreach (sort keys %count) {

in which case the scalar holding the key is$_instead of$m.
Although hashes use a different notation than arrays, one can use hashes
to implement arrays. All one needs to do is write the index using braces
instead of brackets. Thus one would write$x{2}instead of$x[2].Using
hashes instead of arrays is convenient when the indexes are not consecutive
or do not start at 0. The one place where one must be careful when using
hashes is when one is iterating. By default thesortfunction sorts the keys
as strings. If the keys are actually numbers, the order will look rather strange.
For example, “10” precedes “2” as strings. To sort in numerical order specify
{$a<=> $b }after the sort function. For example, if%xis a hash whose
keys are numerical, then the following will print the values in numerical
order:

foreach $i (sort { $a <=> $b } keys %x) {
print("$i: $x{$i}\n");
}

Many other sorting orders can be used by varying the sort order used in the
braces after the sort function. The default order is dictionary ordering which
uses thecmpoperator.
Free download pdf