Perl: Appending and Writing to Files

In our last tutorial we left off on the topic of creating files and manipulating the data therein. In this article we will discuss how to append to a file and how to write to a file. If there is time, we will also discuss working with file checks.

How to Append to a File

Sometimes you want to append or add additional information to a file. To do so is simple. Just open up the file with the original data and add however many lines you wish to the end of the page. Let’s say we want to some data to our superhero.txt file.

Here is what it originally looked like:


  The Incredible Hulk|Super Strength|I rip my pants


  Daredevil|Heightened Senses|I have poor fashion sense due to blindness


  Apache Chief|the ability to grow Very Tall|I wear a skirt

Now are going to add a new row for the superhero I consider to probably be the lamest of all:

  Aqua Man|the ability to communicate with fish|deep fryers and tartar sauce

Our superhero.txt file should now look like this:

  The Incredible Hulk|Super Strength|I rip my pants

  Daredevil|Heightened Senses|I have poor fashion sense do to blindness

  Apache Chief|the ability to grow Very Tall|I Wear a skirt

  Aqua Man|the ability to communicate with fish|deep fryers and tartar sauce

Amazing right?

Of course we can also append data with code, like so:


$my_file="suphero.txt";

open(PLOT,">>$my_file") || die("This file will not open!");

print PLOT "Aqua Man/|the ability to communicate with fish/|deep fryers and tartar saucen";

close(PLOT);

I know that the above code looks a little convoluted. You will notice several differences right off the bat. First, when we open the file we use double quotes after the comma, and we have added two greater than characters (>>) to the front of the filename we wish to open. These two greater than symbols tell the program we wish to append data and not read or overwrite data.

Next we use our buddy the print command, followed by our referencer PLOT, to place the data in our table. As you can see, we use the pipe(|) delimiter again to separate the columns. Before we place the pipes(|) in however, we must first escape using the backslash(/). Finally, we add an n (newline) to the end of the sentence and close our connection.

We could accomplish the same thing using variables:


$my_file="superhero.txt";

$heroname="Aqua Man";

$heropower="the ability to communicate with fish";

$heroweakness="deep fryers and tartar sauce";


open(PLOT,">>$my_file") || die("The file cannot be opened!");

print DAT "$heroname|$heropower|$heroweaknessn";

close(PLOT);

This will have the same affect as our previous code, although it may be a little easier to read and understand.

{mospagebreak title=Writing to Files}

The phrase "writing to files" is a little misleading. When I think of writing to a file, I am really thinking of appending to the file. Why they didn’t just name it Overwriting Files, I will never know, because that is really what you are doing. Basically the original file is overwritten and new data is written in its place.

Let’s say we want to get rid of all the heroes in our database and add news ones to it. We do it the same way we append to a file except for this line:


open(DAT,">$my_file") || die ("The file has died!");

As you can see, we now only use one greater than (>) key. This tells the program that we are writing (or overwriting) data. You assign the new values the same way as before.


$my_file="superhero.txt";

$heroname="Batman";

$heropower="None. He does not need them";

$heroweakness="Slow speech and Action Bubbles";


open(PLOT,">$my_file") || die("The File is dead!");

print PLOT "$heroname|$heropower|$heroweaknessn";

close(PLOT);

If we printed this file, this would be the contents: Batman|None. He does not need them|Slow speech and Action Bubbles

{mospagebreak title=Overwriting Without Deleting Everything}

Okay, so maybe we were a little hasty in overwriting the entire table. To be fair, there is not a way to delete a single line of data with the Overwrite command. But we can trick the program using our gigantic brains. For this example we are going to work with our original four sets of data. We are going to delete Daredevil (our second record it seems) from the table. Observe!


$my_file="superhero.txt";


open(PLOT, $my_file) || die(‘Oops the file is broked!’);

@my_data=<PLOT> ; #stores the data from the file in an array called @my_data

close(PLOT);


splice(@my_data,1,1);


open(PLOT,">$my_file") || die("File won’t open");

print PLOT @my_data;

close(PLOT);

The splice command works by look at the command and removing the array element you indicate (1,1…remember arrays start at the number 0. Since daredevil is the second element, we use 1).

When you are finished, this is the data that will remain in the file:

  The Incredible Hulk|Super Strength|I rip my pants


  Apache Chief|the ability to grow Very Tall|I Wear a skirt


  Aqua Man|the ability to communicate with fish|deep fryers and tartar sauce

{mospagebreak title=How to Delete a File}

We can use the following command to delete the file:


unlink("superhero.txt");

(Note: remember, if you did not put it in the same directory as the code you are writing, you must add the location of the file).

You can do the same thing with variables:


$my_file="superhero.txt";

unlink($my_file);

And voila! Your file is deleted. Of course if you need it later you are screwed, so it is always a good idea to make a backup somewhere in case you need it later.

How To Check a File

There are several ways to test files within Perl. The funniest to me is the Check Existence, which literally checks to see if a file exists. I guess not everyone can have a super human brain like you and me. 

Does it Exist?!?

Here is the code to see if a file exists:


if (-e "superhero.txt")

{

#whatever you want to occur if the file exists

}

The -e tells the code to see if the preceding file name exists. You can do the same thing with a variable too of course.


$my_file="superhero.txt";

if (-e $my_file)

{

#whatever you want to occur if the file exists

}

You can also see if a file exists by measuring the size of the file. For that you would replace -e with -z or -s (z = zero sized file, s= more than zero).


$my_file="superhero.txt";

if (-z $my_file)

{

#whatever you want to occur if the file is zero sized

}

or

 

$my_file="superhero.txt";

if (-s $my_file)

{

#whatever you want to occur if the file is greater than 0 in size

}

You can of course also test if the file has Text or Binary data:


$my_file="superhero.txt";

if (-T $my_file)

{

#whatever you want to occur if the file is a text file

}

and


 

$my_file="superhero.txt";

if (-B $my_file)

{

#whatever you want to occur if the file is a binary file

}

{mospagebreak title=More Ways to Test Files}

There are also ways to test if a file is read, writable, or executable:


$my_file="superhero.txt";

if (-r $my_file)

{

#whatever you want to occur if the file is readable

}


$my_file="superhero.txt";

if (-w $my_file)

{

#whatever you want to occur if the file is writable

}


$my_file="superhero.txt";

if (-x $my_file)

{

#whatever you want to occur if the file is executable

}

And lastly, if you want to test more than one you can use the OR (||), and AND (&&) (ow my brains!) operators.


$my_file="superhero.txt";

if ( (-e $my_file) && (-w $my_file) )

{

#whatever you want to occur if the file exists and is writable

}

Here is a table for a quick reference:

 

File Checks

What it Does

-e

Checks to see if the file exists

-z

Checks to see if a file size is zero

-s

Checks to see if a file size is not zero

-r

Checks to see if a file is readable

-w

Checks to see if a file is writable

-x

Checks to see if a file is executable

-T

Checks to see if a file is a text file

-B

Checks to see if a file is a binary file

&&, ||

And and OR Operators used to check if one criteria or another is true, or if this criteria AND that criteria are true

All right folks. That’s it for this section covering Files. In the next series we will cover how to work with Directories and possibly forms, time permitting.

So swing by often.

Till then…

Google+ Comments

Google+ Comments