The open command can be used to open a file. The basic syntax is
open ( ID, "filename" );
where ID is the ID assigned to the I/O stream.
But how do we tell whether the file is openned for reading, writing, appending, etc? We do so through the use of pipes (as we have been looking at since day one).
By default, open will open a file to read:
open ( ID, "some_file.txt" );
This is equivalent if we used the pipe redirect:
open ( ID, "<some_file.txt" );
If we wish to open a file for writing, we use the pipe redirect into the file:
open ( ID, ">some_file.txt" );
If we wish to append to a file (instead of overwriting it), we would use double pipe redirect:
open ( ID, ">>some_file.txt");
close
When we are finished with a file handle (I/O stream), we should close it:
close ID;
Reading data from a file
There are a number of ways to get data from a file. The most direct way (and the only way we will focus on in this class) is to simply pass the contents from the file handle into a variable (usually an array). If I wanted to take the contents of an I/O stream called "ID" and place them into the variable $a, I would use:
$a = <ID>;
A full sequence where we openned a file, read from it, and closed it would look like the following:
open ( ID, "some_file.dat" );
$data = <ID>;
close ID;