25.10. File Operations

One of the advantages of using CGI programs is that they can read and write to the filesystem, and Perl is no exception. Perl includes quite a few functions for dealing with file IO, covered in the following sections.

25.10.1. Standard Operating Procedure

To access files, there are three operations that you need to perform:

  • Open the file and assign a file handle.

  • Perform file operations (read/write).

  • Close file handle, thereby closing the open file.

In an effort to make programs more uniform, there are three connections that always exist when your program starts. These are STDIN, STDOUT, and SDTERR (these variable names are open file handles).

25.10.2. Opening a File

To open a file, Perl uses (strangely enough) the open function. The open function has the following syntax:

open(FILEHANDLE, "<filename>")

For example, to open the file test.txt you would use code similar to the following:

open(FILEHANDLE,"test.txt") || die "cannot open file";

The preceding syntax will result in the script exiting and displaying "cannot open file" if the open function does not succeed.

The FILEHANDLE can be any valid variable name but should be descriptive to be easily identified as a file handle. One standard practice is to capitalize the file handle variables.

The default operation of the open function is to open a file for reading. To open a file for writing, you need to preface the filename with a >; to append to a file, you would preface the name with >>. Both of these ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.