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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.