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