PERL - File Handling
Now we
shift gears as we introduce file handling. In PERL files are given a name, a
handle, basically another way of saying alias. All input and output with files
is achieved through filehandling. Filehandles are also a means by one program
may communicate with another program.
PERL - Assigning Handles
A filehandle is nothing more than a nickname for the files
you intend to use in your PERL scripts and programs. A handle is a temporary
name assigned to a file. A great filehandle is an abreviated version of the
filename. The example below illustrates how you will use a file handle in your
PERL code.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$FilePath = "home/html/myhtml.html"
sysopen(HANDLE, $FilePath, O_RDWR);
printf HANDLE "Welcome to MYSITE!";
close (HANDLE);
PERL - Files and the die Function
The die function exists in several programming
languages. It is used to kill your scripts and helps pinpoint where/if your
code is failing. We use this function as follows.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$filepath = "myhtml.html";
sysopen (HTML, '$filepath', O_RDWR|O_EXCL|O_CREAT, 0755) or die "$filepath cannot be opened.";
printf HTML "<html>\n";
printf HTML "<head>\n";
printf HTML "<title>My Home Page</title>";
printf HTML "</head>\n";
printf HTML "<body>\n";
printf HTML "<p align='center'>Here we have an HTML
page with a paragraph.</p>";
printf HTML "</body>\n";
printf HTML "</html>\n";
close (HTML);
Now if for some reason PERL is unable to open or create our
file, we will be told. It is good practice to use the die function and we will
be using it more as we dive deeper into file handling.
Perl - File Open
Files are opened using the open and sysopen
function. Nothing fancy here at all. Either function may be passed up to 4
arguments, the first is always the file handle discussed earlier, then our file
name also known as a URL or filepath, flags, and finally any permissions to be
granted to this file.
When opening files as a programmer, there will generally be
one of three goals in mind, file creation, appending files, or trunicating
files.
Create:
Checks to see if the file exists, if not,
perl creates a new file.
Append:
Sets the pointer to the end of the file,
all output following will be added onto the tail end of the file.
Truncate:
Overwrites your existing file with a new
one, this means all data in the old file will be lost.
PERL - Open a File
The following example will open a previously saved HTML
document.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$FH = "filehandle";
$FilePath = "myhtml.html";
open(FH, $FilePath, permissions);
or
sysopen(FH, $FileName, permission);
Files with special characters or unusual names are best
opened by first declaring the URL as a variable. This method removes any
confusion that might occur as PERL tries to interpret the code. Tildas in
filenames however require a brief character substitution step before they can
be placed into your open statements.
PERL - File Permissions
File permissions are crucial to file security and function.
For instance, in order to function, a PERL file (.pl) must have executable file
permissions in order to function on your web server. Also, you may not want all
of your HTML files to be set to allow others to write to them or over them.
Here's a listing of what to pass to the open function when working with
file handles.
Shorthand Flags:
Entities
|
Definition
|
< or r
|
Read Only Access
|
> or w
|
Creates, Writes, and Truncates
|
>> or a
|
Writes, Appends, and Creates
|
+< or r+
|
Reads and Writes
|
+> or w+
|
Reads, Writes, Creates, and Truncates
|
+>> or a+
|
Reads, Writes, Appends,
and Creates
|
O_ Flags:
Value
|
Definition
|
O_RDWR
|
Read and Write
|
O_RDONLY
|
Read Only
|
O_WRONLY
|
Write Only
|
O_CREAT
|
Create the file
|
O_APPEND
|
Append the file
|
O_TRUNC
|
Truncate the file
|
O_EXCL
|
Stops if file already exists
|
O_NONBLOCK
|
Non-Blocking usability
|
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
use Fcntl; #The Module
sysopen (HTML, '/home/html/myhtml.html', O_RDWR|O_EXCL|O_CREAT, 0755);
sysopen (HTML, '>myhtml.html');
PERL - File Creation
Files are opened and created using the same sysopen
function.
Our syntax open(FILEHANDLE, '$filename', permissions,
CHMOD); or sysopen(FILEHANDLE, $filename, permissions, CHMOD);
With sysopen you may also set hexidecimal priviledges;
CHMOD values. Sysopen also requires the declaration of a new module for PERL.
We will be using the Fcntl module for now, more on this later. Below we have
created a basic HTML (myhtml.html) file.
PERL Code:
#!/usr/bin/perl
use Fcntl; #The Module
print "content-type: text/html \n\n"; #The header
sysopen (HTML, 'myhtml.html', O_RDWR|O_EXCL|O_CREAT, 0755);
printf HTML "<html>\n";
printf HTML "<head>\n";
printf HTML "<title>My Home Page</title>";
printf HTML "</head>\n";
printf HTML "<body>\n";
printf HTML "<p align='center'>Here we have an HTML
page with a paragraph.</p>";
printf HTML "</body>\n";
printf HTML "</html>\n";
close (HTML);
myhtml.html:
<html>
<head>
<title>My Home Page</title></head>
<body>
<p align='center'>Here we have an HTML page with a paragraph.</p>
</body>
</html>
myhtml.html-browser view:
Here we have an HTML
page with a paragraph.
Our highlight shows the module we forced PERL to use, and
the sysopen command. FH stands for filehandle, this value can be changed to
whatever the author would like, it is just a way to reference the same file in
a script. We then named the file with read and write priviledges, then told
PERL to check if the file exists, and if not create a new file with 0755 CHMOD
priviledges.
Below is the shorthand method, the difference here is our
filehandle name has changed, and we are unable to set a CHMOD value with this
function.
PERL Code:
open(TEXT,+<newtext.txt.);
printf TEXT "Check out our text file!";
close (TEXT);
We use the printf function instead of print to
actually print our text into the file. Everything inside the printf function is
embeded into our created file.
PERL - Reading from a File
It is possible to read lines from files and input them
using the <> input operator. By placing the file handle inside of
the input operator, your script will input that line of the file.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$HTML = "myhtml.html";
open (HTML) or die "Can't open the file!";
print <HTML>;
close (HTML);
myhtml.pl:
Here we have an HTML
page with a paragraph.
Here we use a tiny PERL script to display several lines of
HTML code. Each line is stored into an array and automatically printed to the
browser in HTML format using the <> input operator.
PERL - Input Array
PERL is able to print out lines of other files with the use
of arrays. Following the example above when we called our HTML file handle
using the input operator, PERL automatically stored each line of the file into
a global array. It is then able to process each element of the array as we
demonstrated in PERL Arrays. This makes it possible to integrate dynamic bits
of HTML code with already existing HTML files.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$HTML = "myhtml.html";
open (HTML) or die "Can't open the file!";
@fileinput = <HTML>;
print $fileinput[0];
print $fileinput[1];
print $fileinput[2];
print $fileinput[3];
print "<table border='1' align='center'><tr>
<td>Dynamic</td><td>Table</td></tr>";
print "<tr><td>Temporarily Inserted</td>
<td>Using PERL!</td></tr></table>";
print $fileinput[4];
print $fileinput[5];
close (HTML);
dynamic.pl:
Dynamic
|
Table
|
Temporarily Inserted
|
Using PERL!
|
Here we have an HTML
page with a paragraph.
To permanently change a file, replace the print
function with the printf function.
PERL - Copying Files
We can duplicate a file using the copy function.
Copy takes two values the URL of the file to be copied and the URL of the new
file. Since we want to duplicate the file in this example, we won't change the
directory path but instead, just give the file a new name. If we used the same
file name or the same URL, PERL will rewrite over the file if permissions
allow.
We also must use a new module, the copy module of course.
PERL Code:
#!/usr/bin/perl
use File::Copy;
print "content-type: text/html \n\n"; #The header
$filetobecopied = "myhtml.html.";
$newfile = "myhtml.html.";
copy($filetobecopied, $newfile) or die "File cannot be copied.";
Here, we have simply duplicated the "myhtml.html"
file and will be using it in further examples.
If we wanted to copy the file to a new directory, we can
edit our variables to match the directory we wish to copy the file to.
PERL Code:
#!/usr/bin/perl
use File::Copy;
print "content-type: text/html \n\n"; #The header
$filetobecopied = "myhtml.html.";
$newfile = "html/myhtml.html.";
copy($filetobecopied, $newfile) or die "File cannot be copied.";
Now we have copied the file from its current directory to
an HTML directory.
When using PERL on the web, it is best to use complete
internet URL. We used a shorthand way in the example but a better solution may
be to hardcode the full URL meaning; http://www.your.com/myhtml.html.
PERL - Moving Files
Moving a file requires the use of the move function.
This functions works exactly as the copy function from above and we send PERL
the same module. The difference is that instead of copying we are 'cutting' the
file and sending it to a new location. It works the same as cutting and pasting
text from an office document to another.
PERL Code:
#!/usr/bin/perl
use File::Copy;
print "content-type: text/html \n\n"; #The header
$oldlocation = "myhtml.html";
$newlocation = "html/myhtml.html";
move($oldlocation, $newlocation);
Now our file has been completly removed from its current
location and placed into the new location.
PERL - Deleting Files
Use the unlink function to delete specific files
from your web server. The best solution is often to set a variable name equal
to the URL of the file you wish to delete.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
$file = "newtext.txt";
if (unlink($file) == 0) {
print "File deleted successfully.";
} else {
print "File was not deleted.";
}
deletefiles.pl:
File deleted successfully.
PERL - Removing Multiple Files at Once
Multiple files can be removed at once if we first create an
array of files to be deleted and then loop through each one. There are several
ways to go about this process.
PERL Code:
#!/usr/bin/perl
print "content-type: text/html \n\n"; #The header
@files = ("newtext.txt","moretext.txt","yetmoretext.txt");
foreach $file (@files) {
unlink($file);
}