Concepts of Programming Languages

(Sean Pound) #1

96 Chapter 2 Evolution of the Major Programming Languages


gaps do not take space in memory, and the iteration statement used for arrays,
foreach, iterates over the missing elements.
Perl includes associative arrays, which are called hashes. These data struc-
tures are indexed by strings and are implicitly controlled hash tables. The Perl
system supplies the hash function and increases the size of the structure when
necessary.
Perl is a powerful, but somewhat dangerous, language. Its scalar type stores
both strings and numbers, which are normally stored in double-precision floating-
point form. Depending on the context, numbers may be coerced to strings and
vice versa. If a string is used in numeric context and the string cannot be converted
to a number, zero is used and there is no warning or error message provided
for the user. This effect can lead to errors that are not detected by the compiler
or run-time system. Array indexing cannot be checked, because there is no set
subscript range for any array. References to nonexistent elements return undef,
which is interpreted as zero in numeric context. So, there is also no error detec-
tion in array element access.
Perl’s initial use was as a UNIX utility for processing text files. It was and
still is widely used as a UNIX system administration tool. When the World
Wide Web appeared, Perl achieved widespread use as a Common Gateway
Interface language for use with the Web, although it is now rarely used for that
purpose. Perl is used as a general-purpose language for a variety of applications,
such as computational biology and artificial intelligence.
The following is an example of a Perl program:

# Perl Example Program
# Input: An integer, $listlen, where $listlen is less
# than 100, followed by $listlen-integer values.
# Output: The number of input values that are greater than
# the average of all input values.
($sum, $result) = (0, 0);
$listlen = <STDIN>;
if (($listlen > 0) && ($listlen < 100)) {
# Read input into an array and compute the sum
for ($counter = 0; $counter < $listlen; $counter++) {
$intlist[$counter] = <STDIN>;
} #- end of for (counter ...
# Compute the average
$average = $sum / $listlen;
# Count the input values that are > average
foreach $num (@intlist) {
if ($num > $average) { $result++; }
} #- end of foreach $num ...
# Print result
print "Number of values > average is: $result \n";
} #- end of if (($listlen ...
Free download pdf