Bookmark and Share

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.

Advertise on Tizag.com

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:

EntitiesDefinition
< or rRead Only Access
> or wCreates, Writes, and Truncates
>> or aWrites, Appends, and Creates
+< or r+Reads and Writes
+> or w+Reads, Writes, Creates, and Truncates
+>> or a+Reads, Writes, Appends, and Creates

O_ Flags:

ValueDefinition
O_RDWRRead and Write
O_RDONLYRead Only
O_WRONLYWrite Only
O_CREATCreate the file
O_APPENDAppend the file
O_TRUNCTruncate the file
O_EXCLStops if file already exists
O_NONBLOCKNon-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');
Bookmark and Share




Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials