Arithmetic, Strings, and I/O in Perl

Tom Kelliher, CS29

Feb. 18, 1997

Announcements:

Learning Perl is on reserve in Mack.

Reading:

Perl 5 How-To: 1.1, 1.6, 1.7, 3.2, 3.3, 7.1, 7.2.

Learning Perl: Chs. 2, 4, 6.

Programming assignment:

Write a program which interactively asks for a file name, then opens and
reads the file, line by line. Each line should be echoed to the screen,
with a line number and a tab (\t) preceding it. (Advanced: In
addition, output the number of words in the file. A word is defined to be
a contiguous sequence of non-space characters.)

#!/usr/contrib/bin/perl -w
# This is a small perl program which demonstrates some file I/O
# operations:
# o File handles.
# o Opening a file for input and checking to see if it opened.
# o Using an opened file.
# o Closing a file.
#
# This program interactively reads a file name and then copies the contents
# of that file to the screen.
print "Enter file name: "; # Get the file name.
$name = <STDIN>;
chop($name);
open(INPUT, $name) || # Try to open the file.
die "Cannot open $name";
print "Contents of $name:\n";
while ($line = <INPUT>) # Print the file on the screen.
{
print $line;
}
close(INPUT); # Close the file.
exit 0;