Contents Up Previous Next

5 File Input/Output

By now you are probably wondering how perl can be used to interact with the external world, and this is where File Input/Output enters the frame.

In perl, file I/O is handled by using sessions: you are opening a file for reading or writing (or both), do with it what you want, and then close it. In perl filehandles are placed on a separate namespace than that of the variables. It is generally marked with a starting asterik (*), which can be omitted if the first letter is a capital one.

To open a file use the open MyFileHandle, $file_path; notation, and to close a file use the close(MyFileHandle); notation. The first characters of $file_path determine whether the file will be open for reading, writing, appending or both. The following table should give you a quick reference:

> Writing (the original file will be erased before the function starts).
< (or nothing) Reading
>> Appending (the file pointer will start at the end and the file will not be overriden)
+< Read-write, or just write without truncating.

The rest of $file_path is the pathname of the file to open relative to the script current working directory (CWD). For instance, the command open I, "<../hello.txt"; opens the file "hello.txt" found a directory below the current directory to reading.

Note

Be careful on opening files whose filenames were inputted from the user. If not properly checked, you may open an improper file, or you may actually run programs (we will learn about that later), or cause unexpected results.

Such badly written code was part of the problem in which the Gibraltar Hack against the PC-Week Linux test server was successful.


Contents Up Previous Next