Home > Articles > Web Development > Perl

Working with Files in Perl

  • Print
  • + Share This
  • 💬 Discuss
Perl is an outstanding language for reading from and writing to files on disk or elsewhere. Begin to incorporate files into your Perl programs by learning how to open, read, write, and test files.

Until now, your Perl programs have been self-contained. They have been unable to communicate with the outside world other than to provide messages to the user and receive input from the keyboard. All of that is about to change.

Perl is an outstanding language for reading from and writing to files on disk or elsewhere. Perl's scalars can stretch to hold the longest possible record in a file, and Perl's arrays can stretch to hold the entire contents of files—as long as enough memory is available, of course. When the data is contained within Perl's scalars and arrays, you can perform endless manipulations on that data and write new files.

Perl tries very hard not to get in your way while reading or writing files. In some places, Perl's built-in statements are even optimized for performing common types of file input/output (I/O) operations.

In this hour, you will learn how Perl can give you access to all the data available to you in files.

In this hour you will learn

  • How to open and close files

  • How to write data to files

  • How to read data from files

  • How to write Perl defensively so that your programs are robust

Opening Files

To read or write files in Perl, you need to open a filehandle. Filehandles in Perl are yet another kind of variable. They act as convenient references (handles, if you will) between your program and the operating system about a particular file. They contain information about how the file was opened and how far along you are in reading (or writing) the file; they also contain user-definable attributes about how the file is to be read or written.

From previous hours you're already familiar with one filehandle: STDIN. This filehandle is given to you automatically by Perl when your program starts, and it's usually connected to the keyboard device (you'll learn more details about STDIN later). The format for filehandle names is the the same as that for variable names outlined in Hour 2, "Perl's Building Blocks: Numbers and Strings," except that no type identifier appears in front of the name ($, @). For this reason, it's recommended that filehandle names be in uppercase so that they do not clash with Perl's current or future reserved words: foreach, else, if, and so on.

NOTE

You can also use a string scalar or anything that returns a string—such as a function—as a filehandle name. This type is called an indirect filehandle. Describing their use is a bit confusing for a primer in Perl. For more information on indirect filehandles, see the online documentation on the open function in the perlfunc manual page.

Any time you need to access a file on your disk, you need to create a new filehandle and prepare it by opening the filehandle. You open filehandles, not surprisingly, with the open function. The syntax of the open function is as follows:

open(filehandle, pathname)

The open function takes a filehandle as its first argument and a pathname as the second argument. The pathname indicates which file you want to open, so if you don't specify a full pathname—such as c:/windows/system/open will try to open the file in the current directory. If the open function succeeds, it returns a nonzero value. If the open function fails, it returns undef (false):

if (open(MYFILE, "mydatafile")) {
  # Run this if the open succeeds
} else {
  print "Cannot open mydatafile!\n";
  exit 1;
}

In the preceding snippet, if open succeeds, it evaluates to a true value, and the if block is run with the open filehandle called MYFILE which is now open for input. Otherwise, the file cannot be opened, and the else portion of the code is run, indicating an error. In many Perl programs, this "open or fail" syntax is written using the die function. The die function stops execution of your Perl program and prints an error message:

Died at scriptname line xxx

Here, scriptname is the name of the Perl program, and xxx is the line number where the die was encountered. The die and open functions are frequently seen together in this form:

open(MYTEXT, "novel.txt") || die;

This line is read as "open or die," which sums up how you will usually want your program to handle the situation when a file can't be opened. As described in Hour 3, "Controlling the Program's Flow," if the open does not succeed—if it returns false—then the logical OR (||) needs to evaluate the right-hand argument (the die). If the open succeeds—if it returns true—then the die is never evaluated. This idiom is also written with the other symbol for logical OR, or.

When you are done with a file, it is good programming practice to close the filehandle. Closing notifies the operating system that the filehandle is available for reuse and that any unwritten data for the filehandle can now be written to disk. Also, your operating system may allow you to open only a fixed number of filehandles; after that limit is exceeded, you cannot open more filehandles until you close some. To close filehandles, you use the close function as follows:

close(MYTEXT);

If a filehandle name is reused—that is, if another file is opened with the same filehandle name—the original filehandle is first closed and then reopened.

Pathnames

Until now, you've opened only files with simple names like novel.txt that did not include a path. When you try to open a filename that doesn't specify a directory name, Perl assumes the file is in the current directory. To open a file that's in another directory, you must use a pathname. The pathname describes the path that Perl must take to find the file on your system.

You specify the pathname in the manner in which your operating system expects it, as shown in the following examples:

open(MYFILE, "DISK5:[USER.PIERCE.NOVEL]") || die;  # VMS
open(MYFILE, "Drive:folder:file") || die;  # Macintosh
open(MYFILE, "/usr/pierce/novel") || die;  # Unix.

Under Windows and MS-DOS systems, pathnames contain backslashes as separators— for example, \Windows\users\pierce\novel.txt. The only catch is that when you use backslash-separated pathnames in a double-quoted string in Perl, the backslash character sequence gets translated to a special character. Consider this example:

open(MYFILE, "\Windows\users\pierce\novel.txt") || die;  # WRONG

This example will probably fail, because \n in a double-quoted string is a newline character—not the letter n—and all the other backslashes will get quietly removed by Perl. As you might guess from Hour 2, "Perl's Building Blocks: Numbers and Strings," one correct way to open the file is by escaping each backslash with another backslash, as follows:

open(MYFILE, "C:\\Windows\\users\\pierce\\novel.txt") || die; # Right, but messy.

You can get rid of the double slashes by using the qq function as well. However, you can also use forward slash (/) in Perl, even under Windows and MS-DOS, to separate the elements of the path. Perl interprets them just fine, as you can see here:

open(MYFILE, "C:/Windows/users/pierce/novel.txt") || die;  # Much nicer

The pathnames you specify can be absolute pathnames—for example, /home/foo in UNIX or c:/windows/win.ini in Windows—or they can be relative pathnames—../junkfile in UNIX or ../bobdir/bobsfile.txt in Windows. The open function can also accept pathnames that are Universal Naming Convention (UNC) pathnames under Microsoft Windows. UNC pathnames are formatted like this:

\\machinename\sharename

Perl accepts UNC pathnames with either backslashes or forward slashes and opens files on remote systems if your operating system's networking and file sharing are otherwise set up correctly, as you can see here:

open(REMOTE, "//fileserver/common/foofile") || die;

On the Macintosh, pathnames are specified by volume, folder, and then file, separated by colons, as shown in Table 5.1.

Table 5.1 MacPerl Pathname Specifiers

Macintosh Path

Meaning

System:Utils:config

System drive, folder Utils, file named config

MyStuff:friends

From this folder down to folder MyStuff, file named friends

ShoppingList

This drive, this folder, file named ShoppingList


A Good Defense

Writing programs on a computer inevitably leads to a sense of optimism. Programmers might find themselves saying "This time it will work" or "Now I've found all the bugs." This notion of pride in your own work is good to a point; innovation comes from a sense that it is possible to accomplish the impossible. However, this self-confidence can be taken too far and turn into a sense of infallibility, which the ancient Greeks called hubris and that can lead to tragedy—now as then. A little hubris every so often can be a good thing; however, excessive hubris always received its punishment, called nemesis, from the gods. That can happen to your programs as well.

NOTE

This observation has been around since computers were first programmed. In his classic work, The Mythical Man-Month (Reading, MA: Addison Wesley, 1975, p. 14), Fredrick P. Brooks says: "All programmers are optimists. Perhaps this modern sorcery [programming] especially attracts those who believe in happy endings and fairy godmothers. [ . . . but . . . ] Because our ideas are faulty, we have bugs; hence our optimism is unjustified."

Until now, all the snippets and exercises you've seen have dealt with internal data (factoring numbers, sorting data, and so on) or with simple user input. When you're dealing with files, your programs talk to an external source over which they have no control. This will also be true in situations you'll encounter in later hours, when you're communicating with data sources not located on your computer, such as networks. Here is where nemesis can strike. Keep in mind that if anything can go wrong, it will, so you should write your programs accordingly. Writing your programs this way is called defensive programming, and if you program defensively, you'll be a lot happier in the long run.

Whenever a program interacts with the outside world, such as opening a filehandle, always make sure the operation has been successful before continuing. I've personally debugged a hundred or more programs in which the programmer requested the operating system to do something, didn't check the results, and caused a bug. Even when your program is just an "example" or a "quickie," check to make sure that what you expect to happen really happens.

dieing Gracefully

The die function is used in Perl to stop the interpreter in case of an error and print a meaningful error message. As you've seen earlier, simply calling die prints a message like the following:

Died at scriptname line xxx

The die function can also take a list of arguments, and those arguments are printed instead of the default message. If the message is not followed by a newline character, the message has at scriptname line xxx appended to the end:

die "Cannot open";   # prints "Cannot open at scriptname line xxx"
die "Cannot open\n";  # prints "Cannot open"

A special variable in Perl, $!, is always set to the error message of the last requested operation of the system (such as disk input or output). Used in a numeric context, $! returns an error number, which is probably not useful to anyone. In a string context, $! returns an appropriate error message from your operating system:

open(MYFILE, "myfile") || die "Cannot open myfile: $!\n";

If the code in the preceding snippet fails because the file does not exist, the message prints something similar to Cannot open myfile: a file or directory in the path does not exist. This error message is good. In your programs, a good error message should indicate what went wrong, why it went wrong, and what you were trying to do. If something ever goes wrong with your program, a good diagnostic can help in finding the problem.

CAUTION

Do not use the value of $! to check whether a system function failed or succeeded. $! has meaning only after a system operation (like file input or output) and is set only if that operation fails. At other times, the value of $! can be almost anything—and is wholly meaningless.

Sometimes, though, you don't want the program to die—just issue a warning. To create this warning, Perl has the warn function. warn works exactly like die, as you can see here, except that the program keeps running:

if (! open(MYFILE, "output")) {
  warn "cannot read output: $!";
} else {
  :  # Reading output...
}
  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus