This is part 20 of my series, Basics of ActivePerl. In this part of the series, we see how to access files in ActivePerl. I assume that you have read the previous parts of the series before reading this one, because the knowledge here is based on knowledge gained from the previous parts of the series. We shall consider only text files and those, which are in the working directory (so we shall not need to bother about directory path). This means that your test code should remain in the working directory (cgi-bin). Everything said in this tutorial is applicable to traditional Perl.
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
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. 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 copied to the file in 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. When you close the file, effectively closing the copy, the content of the copy in memory is copied to the disk for the first time. 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 copied to the file, which might or might not have existed, in the disk.
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:
close(filehandle)
The parentheses has the filehandle you used in opening the file.
Mode
In the open function, the mode can be < or > or >>. You can have a space between the mode and the filename.
>: 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.
Illustration
The following code segment should create a new file and writes 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 file mane, in double quotes. If the file, myfile.txt did not exist in the working directory (where your executing ActivePerl 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, 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 saved to disk when the close function is executed.
If the filehandle is omitted for the print function, in our case, the line (string) will go to the browser.
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;
print "Content-Type: text/html\n\n";
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 (you should not have any output at the browser). 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;
print "Content-Type: text/html\n\n";
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
We 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 saved.
use strict;
print "Content-Type: text/html\n\n";
if (open(fHandle, "< myfile.txt"))
{
my @lines = ;
for (my $i=0; $i {
print $lines[$i]; print "
";
}
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 = ;
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 above 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 copy in memory. Close the file and the array content copied including 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;
print "Content-Type: text/html\n\n";
my @lines;
if (open(fHandle, "< myfile.txt"))
{
#read from file copy into array
@lines = ;
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 {
print fHandle $lines[$i]
}
close(fHandle);
}
Use your operating system to open the file, myfile.txt and note that the three lines that were there have been replaced.
Well, we have come to the end of this tutorial. We continue in the next part.
Chrys
Published by Chrys Forcha
I have more than 10 years experience in computer programming, software, electronics and telecommunications. I have a First Degree in Electronics and a Master's Degree in Technical Education. As well a... View profile
- ActivePerl Basic SyntaxIn this part of the series, I give you the basic syntax of ActivePerl.
- Some ActivePerl Predefined SubroutinesIn this part of the series, we look at some ActivePerl predefined subroutines.
- ActivePerl Foreach LoopIn this part of the series, we look at the foreach-loop, which is an alternative to the for-loop.
- Introduction to ActivePerl Special VariablesIn this part of the series, we look at what is called ActivePerl Special Variables.
- White Space in ActivePerlIn this part of the series, I explain what is white space and how it is used in ActivePerl.
- Basics of ActivePerl Reference
- ActivePerl Arrays
- ActivePerl Subroutines
- Just What is a Tickler File?
- PHP File Handling Basics
- Basics of ActivePerl Variables
- Basics of ActivePerl Variable Scope



