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