Home > Articles > Web Development > Perl

Working with Files in Perl

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.
This chapter is from the book

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...
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020