10.1 Text Transformations 219
while (<>) {
chomp;
push(@table, [split]);
}
$size = @table;
print("Table size is $size\n");
Program 10.6 Reading a file of records into a 2D array
tables. Once one has a concept of an array, it is easy to represent these other
mathematical structures. A matrix, for example, is just a vector of vectors, so
to represent it in Perl, one simply constructs a array whose items are them-
selves arrays.
Consider the task of reading all of the fields of all the records in an input
file. The array will have one item for each record of the data file. Each item,
in turn, will be an array that has one item for each field of the record. In
other words, the data will be represented as an array of arrays, also called a
two-dimensional arrayordatabase table. It is very easy to create such a table in
Perl. In program 10.6, the array is constructed, and its size is printed.
Thepushprocedure adds new items to the end of a list. In this case, it
adds a new record to the table array. Each record is obtained by splitting the
current line. Recall thatsplitby itself splits the current line into fields that
were separated by spaces.
The opposite ofpushispop. It removes one item from the end of a list.
There are also procedures for adding and removing items from the beginning
of a list. Theshiftprocedure removes the first item from a list. Unlikepush
andpop,theshiftprocedure changes the positions of all the items in the
list (e.g., the one in position 1 now has position 0). The opposite ofshiftis
unshift, which adds items to the beginning of a list.
The brackets aroundsplittell Perl to maintain the integrity of the record.
Without the brackets, the fields of the record would be pushed individually
onto the array resulting in a very large one-dimensional array with all of the
fields of all of the records.
Brackets around an array tell Perl that the array is to be considered a single
unit rather than a collection of values. The term for this in Perl isreference.It
is similar to the distinction between a company and the employees of a com-
pany. The company is a legal entity by itself, with its own tax identification