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.
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.