Broad Network

File Accessing Basics in Perl

Perl Basics Part 19

Perl Course

Foreword: In this part of the series, I give you the basic explanation of how to access files in Perl.

By: Chrysanthus Date Published: 29 Mar 2015


This is part 19 of my series, Perl Basics. In this part of the series, I give you the basic explanation of how to access files in Perl. I assume you have read the previous parts of the series before reaching here, because the knowledge here is based on knowledge gained from the previous parts of the series. I will consider only text files and those, which are in the working directory (so we shall not need to bother about directory paths). This means that your test code should be in the working directory. Everything said in this tutorial is applicable to traditional Perl.

File Handle
In order for you to use a file in the hard disk or some other drive, you have to do what is called opening the file. With this the content of the file is copied into memory. Whatever you want to do to the file (modifying the file, adding text to the end of the file, or just reading the file) you do it to the copy in memory and it is reflected in the disk. After that you have to do what is called closing the file.  When a file is closed, the content of the copy in memory is erased and any text that had not been copied to the disk is copied to the disk. Any modification of the copy in memory or adding of text to the end of the copy is reflected in the file in the disk after closing.

A file may not exist in the disk. This means you have to create it. For this purpose, you still have to use the opening process (see below). An empty copy for the newly (not existing) opened file is created. You send information to this copy (which goes to the disk as well). When you close the file, effectively erasing the copy, any content that had not been copied to the disk, is copied to the disk. Closing a file means putting an end to the association between the copy in memory and the corresponding file in the disk, after the content of the copy has just been completely copied to the file, which might or might not have existed, in the disk. Closing the file also erases the content in memory (frees memory).

Note: the content (copy) in memory is the file content copied from disk, if the file existed in the disk before it was opened.

The copy in memory has a special type of variable called a filehandle. You give whatever name you want for this filehandle. You use it to open and close the file; you use it to write to or read text from file. Note: filehandle is written as filehandle, not as file handle.

The open and close function
To open a file, you need the predefined open function. To close a file you need the predefined close function. In simple terms the syntax for the open function is,

    open(filehandle, "mode filename");

The parentheses are optional. The filehandle is a name you give; it is not preceded by $. In the opening process (open function), it is declared and the file copy in memory is assigned to it, without you knowing. So you do not need to have declared it before you use it in the open function.

In simple terms the syntax for the close function is:


The optional parentheses have the filehandle you used in opening the file.

In the open function, the mode can be < or > or >>. You can have a space between the mode and the filename.

<: means open file only to read its content.
>: means open file to write content; erase any previous content that the file might have had; if file did not exist in disk, create one.
>>: means open for appending (add text to the end of file). Any text you write to the file goes to the end.

The following code segment should create a new file and write three lines to it:

open(fHandle, "> myfile.txt");
print fHandle "This is the first line.\n";
print fHandle "This is the second line.\n";
print fHandle "This is the third line.\n";
close (fHandle);

It begins with the open function. The first argument is the filehandle (you choose your name). The second argument has the mode and filemane, in double quotes. If the file, myfile.txt did not exist in the working directory (where your executing Perl Script resides), a new one will be created. If it existed in the working directory, all its previous content will be erased.

To send a line of text to the file you need the print function, followed by the filehandle. You end each line you send with the newline character (\n). Each line sent is a string. Because of the newline character, when the file is saved (closed), and you open it with your text editor, you will see each of the strings in a separate line. These lines are all sent to the copy (empty) of the file in memory. The copy is being saved to disk until the close function is executed.

What if the opening Process failed?
The opening process may fail. If your disk has bad sectors, the opening process may fail. If it fails, it means nothing is copied to memory. The open function returns true is it succeeds and false if it fails. So you should always check if the open function succeeds before execution could continue. The above code should be written as follows:

use strict;

if (open(fHandle, "> myfile.txt"))
        print fHandle "This is the first line.\n";
        print fHandle "This is the second line.\n";
        print fHandle "This is the third line.\n";

        close (fHandle);

Read and try the above code. If the open function fails the if-block is not executed. You do not necessarily have to write your content to file, line by line. You can send all the lines as one string. The following code illustrates this

use strict;

if (open(fHandle, "> myfile.txt"))
        print fHandle "This is the first line.\nThis is the second line.\nThis is the third line.\n";

        close (fHandle);

Reading a File
You have seen how to write to a file (above). Here, lets us see how to read the contents of a file. The following code would read the content of the file we created above (and automatically saved).

use strict;

if (open(fHandle, "< myfile.txt"))
        my @lines = <fHandle>;

        for (my $i=0; $i<@lines; ++$i)
                print $lines[$i]; print "\n";

        close (fHandle);

In the open function, the mode < is used. The content (copy in memory) of the file is read into an array in one statement. This statement is,

        my @lines = <fHandle>;

The <> operator is used. Inside the operator you type the filehandle. All the content is read into the array, @lines. Each line in the file goes as a string into one cell of the array. The for-loop displays the content of the array. Read and try the code.

Simple Editing of Text Files
A simple way to edit a file is as follows:

Open the file for read-only (the < mode). Copy the contents of the file into an array. Close the file. Next, modify the contents of the array. Open the file again, but this time, with the mode, >. This mode will erase the previous content of the file. Next copy the contents of the array to the file. Close the file and the array content copied having the file changes, would be saved to disk. In that way you would have modified the file. The following code illustrates this. Read and try it.

use strict;

my @lines;

if (open(fHandle, "< myfile.txt"))
        #read from file copy into array
        @lines = <fHandle>;

        close (fHandle);

#change all the array elements
$lines[0] = "This is line A.\n";
$lines[1] = "This is line B.\n";
$lines[2] = "This is line C.\n";

#implement changes
if (open(fHandle, "> myfile.txt"))
        for (my $i=0; $i<@lines; ++$i)
                print fHandle $lines[$i]

Use your operating system to open the file, myfile.txt and note that the three lines that were there have been replaced.

Note: a line of text can also mean a paragraph.

Well, we have come to the end of this tutorial. We continue in the next part.


Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course



Become the Writer's Fan
Send the Writer a Message