Search & Replace << Files - 1 >> Files - 2
Files with PERL are usually used to gather and store information. This page will show how to work with normal files, not with a database such as MySQL or Access.

The following examples will refer to a file called mycolors.dat which is a simple text file holding the following information :


The dat extension stands for DATA. You can actually use a txt extension instead if that is your preference.

As like any other file reference, be sure to include any subdirectory references if the files you are working with are in different locations than the calling script.

The first thing to do when working with a file is to OPEN it. Once it is open you can make changes or process the information.

When opening a file, a file variable name called a FILE HANDLE is specified. This will be used to perform other operations on the opened file further down. Filename is the name of the file you want to open.

open (filehandle, filename);

If the openning of the file was a success, the statement will actually produce a true return value. Knowing this, you can use statements such as an IF statment to determine if the operation was successful or not.


print "Content-type: text/html\n\n";

if (open (example, "mycolors.dat")) {
print "The file opened successfully \n";
else {
print "File could not be opened \n $!";

In the else print statement, you should notice the $! at the end. This is a built in PERL command that will print the error message that has occured.

Now to introduce two functions are handy working with files and directories : DIE and WARN. Rather ominous sounding aren't they? These functions can be used with other statements by using the OR operator || or using any other decision making type of statement.

open (example, "example.txt") || die ("Could not open file \n $!");

open (example2, "nofile.txt") || warn ("Could not open file \n $!");

If the operation on the left side of the OR operator does not return a "true" value, the DIE or WARN functions are executed. Each of these functions can be used on their own or you have the option of displaying an error messasge.

Here is the difference between these two functions : The DIE function terminates the program. The WARN function simply outputs the error message then keeps going with the rest of the program.

The first line will attempt to open "example.txt". If the file cannot be opened, the die function gets executed and the program terminates. The second line will attempt to open "nofile.txt". This fle does not exist, so the warn funciton gets executed, which simply prints the warning message along with the actual error saved in the $! variable.

Closing a file is just as easy as opening it. Just use the same file handle you started with and use the close command.
close (filehandle);
Search & Replace << Files - 1 >> Files - 2

Advertise in the banner along the top, Click here!

Valid XHTML 1.0 Transitional Valid CSS! Text Link Ads