Perl File Management
Opening and closing files
-
One of the main resources that your server provides is a file management
system. CGI scripts, for example, use a multitude
of supporting files in the server's file system such as temporary files,
counter files, user files, data files, setup files, and libraries. Perl
includes several excellent tools for working with these files.
-
First, Perl gives your scripts the ability to open files using the open
function. The open function allows you to create a "filehandle" with which
to manipulate a file. A filehandle is another name for a connection between
the script and the server. Often, filehandles manage connections between
the script and standard input, output, or error, however, in the case of
open, any file can be read into a filehandle using the syntax:
open ([FILE_HANDLE_NAME], "[filename]");
For example, we might open a data file for reading using
open (DATA_FILE, "inventory.dat");
In this case, all of the lines of inventory.dat will be read into the filehandle
"DATA_FILE" that Perl can then use within the program. However, you must
also close a file once you are done with it. The syntax for closing a file
is as follows:
close ([FILE_HANDLE_NAME]);
Finally, Perl gives you the ability to execute an error routine if there
is a problem opening a file. The "or" logical
operator is sometimes discussed in terms of a short circuit. For instance,
the logic of the "or" operator is such that if the first expression evaluates
to true, there is no need to evaluate the next. On the other hand, if the
first expression evaluates to false, the second expression is executed.
Thus, using the double pipe (||) operator, you can specify the default
action to perform if an "open" fails. In CGI applications, the alternate
action executed is usually something like the subroutine, CgiDie located
in cgi-lib.pl (discussed
later today). For example, the following routine would execute the CgiDie
subroutine if there was a problem opening "address.dat".
open (ADDRESS_BOOK, "address.dat") ||
&CgiDie("Cannot open address.dat");
Thus, if the script has a problem opening a needed file, the double pipe
(||) operator provides a convenient and elegant way to quit the program
and report the problem.
Additional Resources:
Formatting
Control Structures
Table of Contents
Reading a File Line
by Line
|