Thursday, October 30, 2008

How to read a file in PERL

The open() function

Data files are opened in Perl using the open() function. When you open a data file, all you have to do is specify (a) a file handle and (b) the name of the file you want to read from.

As an example, suppose you need to read some data from a file named "checkbook.txt". Here's a simple open statement that opens the checkbook file for read access:

open (CHECKBOOK, "checkbook.txt");

*** Use complete filepath. Generally its a good practice. Replace single slash with double slashes in file-path

In this example, the name "CHECKBOOK" is the file handle that you'll use later when reading from the checkbook.txt data file. Any time you want to read data from the checkbook file, just use the file handle named "CHECKBOOK".


Example - opening a data file and reading from it

Now that we've opened the checkbook file, we'd like to be able to read what's in it. Here's how to read one line of data from the checkbook file:

$record = ;

Pretty simple, eh? After this statement is executed, the variable $record contains the contents of the first line of the checkbook file. The "<>" symbol is called the line reading operator, and in this example we've put the checkbook file handle in the line reading operator, indicating that we'd like to read a line from the checkbook file.

Of course, instead of reading just one line of data, you may want to operate on many lines of data in the checkbook file. Suppose, for example, you wanted to print every record of information from the checkbook file. Here's the code to (a) open the checkbook file, (b) print each record from the file, and (c) close the file when you're finished working with it:

   open (CHECKBOOK, "checkbook.txt");

while ($record = ) {
print $record;
}

close(CHECKBOOK);

Notice the use of the close() statement in this example. You always want to close a file when you're finished reading from it, and since the while loop reads through the entire file, there's not much else to do when you're finished except close it.


No comments: