Working with Data Files

So far all we have done is feed back to the user data they have already entered.

It would be useful to also be able to store data received in a file at the server end.
This would allow us to manipulate and send the data to other users when requested.
This is how web chat programs, guest books and counters work.

Example
Writing to a textfile

# First open the file 'textfile' to allow us to write to it
# or die if there is a problem and send an error message
open(infile,">textfile.txt")|| die "Cannot open file $!";
# Now write the value of the variable $fred to the filehandle infile
print infile $fred;
close(infile);
 # Now close the textfile.

Reading from a text file

#opens the file textfile to allow us to read from it
open(outfile,"<textfile.txt")|| die "Cannot open file $!";
while ($line=<outfile>)
#reads each line of the file to a variable called $line
   {print $line;}

# prints the line to the screen
close(outfile);
#closes the textfile.

Reading from a text file into an array
This variation reads a textfile into an array of lines called @file.
This can be very useful.
It allows us to use the array functions such as Sort or Reverse.

#opens the file textfile to allow us to read from it
open(outfile,"<textfile.txt")|| die "Cannot open file $!";
@file= <outfile>;
	#reads each line of the file to the array @file
foreach $line (@file){print $line;}
#display each element of the array
close(outfile);
#closes the textfile.

Appending to an existing textfile

#opens the file textfile to allow us to write to it
open(infile,">>textfile.txt")|| die "Cannot open file $!";	
   print infile $fred;
#appends the contains of $fred to the file
close(infile);
#closes the textfile.