About Me

Friday 20 April 2012

PERL - File Creation

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.

0 comments:

Post a Comment