Perl: Working with Files

In our last series of tutorials we worked with Conditionals and Loops to create some basic Perl programs. This time around we are going to be working with files. Text files, CGI files, PL files, boiled files, fried files, Files Benedict, steamed Files. Okay, so I was kidding about the steamed Files.

How to Create a File

Creating a file to read from in Perl is pretty simple. Simply open up a .txt file and enter the following data:

  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

When you enter the data, note a few things. First, there are no headers here. Second, we separate each column of data with a pipe(|) symbol. And third, each line of data is separated by pressing the Enter key. Note that nothing should appear on the blank lines, not even a space. This is because when Perl reads it, it will read that line as a new row of data. 

When you finish entering the data, save the file. You can leave it as a .txt file if you like. The only downside to this is that the data will be visible to any users who happen upon your page. If you want to limit visibility of the data, you can save it as a .cgi or .pl file, depending upon your host. For simplicity’s sake, save the file (use the name super.txt) in the same directory as you are saving your script. If you don’t, you will have to point to the directory where your file is being saved.

At this point we could set permissions, but I will save that for another time. Setting permissions allows you to choose whether the file can only be read, can be edited, neither, or both.

{mospagebreak title=How to Open a File}

Before you can read the script, you have to open it. Unless you are Superman and have X-ray vision. And even then you might want to lay off the x-ray vision; get it mixed up with your laser eye beams and you can say good-by to that Super Hero pension check.

The syntax for opening a file is: open(HANDLE, “FileName/Location”); Since we are saving our file and script in the same directory, we don’t need to worry about location in this instance. Handle is used to reference the file when you read it and close it. Here is a sample of how it should look:


open(PLOT, “super.txt”);

You can also store the file name as a variable if you like, so that you can change it more easily in the future:


$my_file=”super.txt”;

open(PLOT, $my_file) || die(“I refuse to open your file!”);

The above code does several things. First, it creates a variable named $my_file and adds the value “super text” to it. Then we open the file, referencing it with the newly created variable. Lastly, I added an OR to the program, that states either load the program, OR create a pop-up alert that tells the user: I refuse to open your file! We do this to alert the user in case there is a problem opening the file.

{mospagebreak title=How to Read a File}

Now that we have opened our file, we can read from it. One way to do this is to assign the data within the file to an array. Behold!


$my_file=”super.txt”;

open(PLOT, $my_file) || die(“I refuse to open your file!”);

@my_data=<PLOT>;

In the example above, we again create a variable named $my_file and store the name of our file within it (super.txt). Next, we open the file using the word PLOT as our Handle, and using the newly created variable. We add the OR and the DIE command in case the file encounters a problem while loading. Lastly, we create an array named @my_data to store the data of our file, super.txt. Note that we reference our file with the PLOT handle.

How to Close a File

After we read the data we will want to close the file. To do so, we simply add close(Plot); to our code, like so:


$my_file=”super.txt”;

open(PLOT, $my_file) || die(“I refuse to open your file!”);

@my_data=<PLOT>;

close(PLOT);


I know what you are thinking: that sure was easy. Well don’t get too cocky you slacker. We still haven’t learned how to work with that data yet.

{mospagebreak title=Manipulating Data}

Now that we have read the contents of our file, let’s put that lazy, good for nothing data to work. As you may or may not have guessed, our table of data consists of super hero names, their super powers, and their weaknesses. So for instance, the Indian super hero Apache Chief has the ability to grow tall; unfortunately he also wears a man-skirt, and people can see under it when he does, which is a weakness. Similarly, the Incredible Hulk transforms in a super strong behemoth, but when he does so, his pants explode. I mean, talk about a weakness. The guy has to buy new pants every time he gets angry.

Let’s create a program that utilizes all of the data in the file:


#!/usr/bin/perl


$my_file=”super.txt”;


open(PLOT, $my_file) || die(“I refuse to open your file!”);

@my_data=<PLOT>;

close(PLOT);


print “Content-type: text/htmln”;

print “<HTML><BODY>”;


foreach $superhero (@my_data)


{

chop($superhero);

($hero_name, $hero_power, $hero_weakness)=split(/|/,$superhero);

print “My name is $hero_name, my super power is $hero_power, and my weakness is $hero_weakness. I hate my life.”;

print “<BR>nn"

}


print “</BODY></HTML>”;



The above code will print out the text:

  My name is The Incredible Hulk, my super power is Super Strength, and my   weakness is I rip my pants

  My name is Daredevil, my super power is heightened senses, and my weakness is I have poor fashion sense due to blindness

  My name is Apache Chief, my super power is the ability to grow very tall, and my weakness is I wear a skirt

{mospagebreak title=How the Code Works}

First we create a variable named $my_file to hold the name of our file, and assign it the value super.txt. Next we open the file, read from it, and close it, storing the data in an array called @my_data. Next we create some simple HTML headers so it will print to a web page, and then we go on to create a foreach loop, that will loop though the data in our array. We create a new variable named $superhero which will hold each line of data in our file (it only holds one line at a time; as it passes through the loop each time a new line replaces the old). Next, we use the chop method to cut off our Enter Key data (we don’t want this in our variable, or it will mess up our print out).

Next we create three variables to hold the three columns that reside within our data file. Then to assign a value to these variables (again, the data in the variables changes to the next line on each pass through the loop), we use the Split Method. If you recall from before we used the pipe(|) symbol to separate the columns in our data file. Now we are going to use the same separator to split up our data. Since the pipe(|) character is a special character in Perl, it must be escaped with a backslash(), hence the weird code:/|/ .

Finally we use the data in our newly created variable to print out text to the browser. And of course we finish by closing out our HTML tags.

Well, you should now have a good understanding of how to create files, open files, read them, store their data into variables, close them, and manipulate that data. In our next tutorial we will discuss how to append to files, and how to write to files when you get lonely and miss them. So check back often.

Till then…

Google+ Comments

Google+ Comments