Printing
Printing is accomplished via the print statement. What follows can be a string, a number, a variable or a combination of them. Variables are evaluated on the fly inside a print statement. Whatever is printed goes to standard out, so it will be displayed on the screen if you run perl from the command line, or it will be sent to the web server if you are using CGI. For the web server to recognize you are printing HTML, you need to print the HTML header before you print anything else.
print $foo;
print "Hello World";
print "Hello $name how are you today?";
Getting Data From your HTML Forms
This is rather easilly accomplished with a libray file called cgi-lib.pl. Inside it is a routine that will read and parse the form data sent to your script and allow you to access your form elements. To use this, you must first download the cgi-lib.pl file, place it in the same directory as your script, and add the two lines to your script, preferably near the top:
require "cgi-lib.pl";
&ReadParse;
This will include the library file and allow you to call the subroutine "ReadParse" which will do the work for you. After that, to refer to one of your form variables, you use this method:
$in{"variableName"};
Where variableName is what you put in the NAME="" attribute on the form. Note that $in{"variableName"} returns a string, and is just like any other variable (it only looks funny for now). The variable "in" is really a hash table, and "variableName" is a key for one of its components. All of the components of in are the values from our form.
Reading data from a file
Another common operation is opening a file and getting the information from it. The three statements below will open a file, stuff the entire file into an array, and close the file. From then on, you can access the data using the array.
open(FILE, "filename");
@lines=<FILE>;
close FILE;
Each line is one element in the array "lines." To print the first line of the file, do this:
print $lines[0];
Or to reprint the entire file, do this:
print @lines;
Writing Data to a File
There is only a minor difference when writing to a file. But please note that when you write to a file, the previous contents are erased for good and are replaced by what you write to it. There is also a way to append data to a file, and in this case, the original data is preserved while what you print is added to the end of the file.
To overwrite a file:
open(FILE, ">filename");
To append to a file:
open(FILE, ">>filename");
In order to print to the file, use the filehandle, FILE, with the print statement:
print FILE "This will go into the file";
Make sure you close the file after you are done printing to it:
close FILE;