CS 29
Feb. 27, 1997
Here is the 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.)
Some of you have discovered that this program is in the book. That's good and bad. It's good in the sense that you've demonstrated good search skills. It's bad if you quickly ``looked up'' the answer without trying to solve the problem on your own.
Here's the strategy:
^u
(hold down the ``ctrl'' key and press the ``u''
key) and start over.
TERM = (hp)Type vt100 and press enter. You should now see the shell prompt:
[1] %(This is what my prompt looks like. Yours may be different.) This prompt is how the system tells you it's waiting for a command from you. How nice to be waited upon like this.
#!/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); if (!open(INPUT, $name)) # Try to open the file. { die "Cannot open $name"; } print "Contents of $name:\n"; $line = <INPUT>; while ($line) # Print the file on the screen. { print $line; $line = <INPUT>; } close(INPUT); # Close the file. exit 0;What's really important here is that you understand what each statement of the program does. Do you?
chmod u+x
followed by your file name. Now run the command
ls -l
. (The
period is a part of the sentence, not the command.) The beginning of the
line for your file should start off with -rwx
. If it doesn't, stop
and call me over.
./hw1.pl
(substitute the file
name you chose). Did your program do what you expected? What happens if
you type in the name of a non-existent file? Did the program do what you
expected.