Linguistics 408/508 |
Fall 2003 |
Hammond |
open()
command, then reading from it, and finally closing
the handle with close()
(example).
It's really easy to make a mistake creating a file handle,
so it is customary to add a test to let you know if something has gone wrong.
Using the or
operator, we can add a command that will only be
executed if the open()
command fails. We use the
die()
command which prints a string and ends the program without
execuating any more commands (example).
Finally, we frequently want to read all the lines of a file until there
are none left. There are two ways to do this. One is to use a
while
-loop (example), and the
other is to use an array (example).
File output is rather similar, but with several glitches. Be
careful; it's easy to mess this up and accidentally overwrite important
files! First, one uses the "redirection" operator
>
when one creates the file handle. Then one uses print with
the new file handle (example). To avoid
doing dangerous things, I strongly encourage you to do all your
playing with file output in some new directory on your computer where there
are no important files.
print()
statement.