Bookmark and Share

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.

Advertise on

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:


print "content-type: text/html \n\n"; #The header
$FilePath = "home/html/myhtml.html"
sysopen(HANDLE, $FilePath, O_RDWR);
printf HANDLE "Welcome to Tizag!";
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:


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.

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