untitled

(ff) #1

218 10 Transforming with Traditional Programming Languages


@lines = <>;
$size = scalar(@lines);
print("The input file has $size lines.\n");

Program 10.5 Reading an entire file into an array

one might expect, this is used frequently in Perl programs, although it does
not necessary appear explicitly. In fact, in this case it can be omitted because
assigning an array to a scalar tells Perl that the array is to be converted to a
scalar. In the case of hashes,scalargives information about the structure
of the hash that is usually not very useful. To get the size of a hash use
scalar(keys(%h)). This gives the number of keys in the hash.
One might think that one can simplify the last two lines of program 10.5 to
the one statement

print("Table size is scalar(@table)\n");

but this does not work. In a quoted string, the special meaning ofscalaris
lost. The string “scalar” will be printed verbatim, and thescalarfunction
will not be invoked. Quoted strings know how to deal with variables, but
they do not understand computations in general. One can get around this
restriction in two ways:


  1. Compute the information in separate statements using a number of vari-
    ables, and then combine them into the string to be printed. This is the
    technique that has been used so far.

  2. Use string concatenation. Once a computation is outside a string, then
    it will be performed as expected. Strings are concatenated using the pe-
    riod character. In a print statement one can also use commas. The print
    statement above can be done using this statement:


print("Table size is ". scalar(@table). "\n");

or by using commas instead of periods.

Arrays are a versatile technique that can be used for lists of values as well
as for representing the mathematical notion of a vector. It is natural to con-
sider how to represent other mathematical structures such as matrices and
Free download pdf