CIW Course Revision Site

Perl - File Input and Output

In a Nutshell - CIW Course Section 2, Part B2, Chapter 6

 

Filehandles

A filehandle provides a connection to a system device such as a disk file, the computer keyboard, or the computer screen. By convention, filehandles are in uppercase characters and are not prefixed with any special character. Filehandles are assigned when you use the open statement to open a connection to a file.

open(MYFILE, "mytextfile.txt");

Perl has three standard filehandles: STDIN, STDOUT and STDERR, these are, respectively, the keyboard, the screen, and the standard error output (usually the screen).

Filehandles, like other identifiers, occupy their own namespace, so MYFILE, $myfile, %myfile and @myfile can all be used, safely, within the same scope.

Open Function

A filehandle will open a file in a number of modes and this is specified with special operators in the filename used by the open function. By default, and without any special character prefix, a file is opened in read-only mode.

File Open Operators
"<mytextfile.txt" Explicitly opens the file for reading
">mytextfile.txt" Opens the file for writing, new file
">>mytextfile.txt" Opens the file for append
"+<mytextfile.txt" Opens the file for read and write
"+>mytextfile.txt" Opens the file for reading and writing, truncating the file first.

Reading data

The simplest and most common way of reading data from a text file is to enclose the filehandle in angle brackets in the same you you would read from the standard input. The data returned in this manner can be retrieved from the special variable "$_".

open(MYFILE, "mytext.txt") || die "Failed to open file: $!";
while (<MYFILE>)
{
print("$_");
}

Notice the "$!" symbols used in the die expression, this inserts the error message for any failure. Also note that I haven't included the normal new line metacharacter "\n" in the print statement, this is because the line returned by <MYFILE> includes the EOL character.

The read function can be used for binary data, see the next chapter for more information.

Writing Data

Writing data to a file adds a parameter to the print function, used to identify the filehandle to use for the operation.

print OUTHANDLE "Text to be written to file.\n";

There is no comma between the filehandle and the expression to be output. Including one is the most common gaffe in Perl programming.

Design by Stephen

Certified Internet Webmaster

Page last Edited: 10 Nov 2011