Thursday, January 6, 2011

File handling in Perl


The following example shows how to write few lines in a file named "test.txt" 
in the working directory through a Perl script.
After writing to the file, "test.txt" should contain the following:
-------------------
|Name:James Dcosta|
|Age:32           |
|Gender:Male      |
-------------------


#!/usr/bin/perl

print "content-type: text/html \n\n"; 

open(FL,">./test.txt"); # Opening the file in write mode. FL here represents the file handle required and can be any non keyword text

flock(FL,2); # Locking the file for writing

print FL "Name:James Dcosta\n"; # Writing the first line in the file followed by a line break at the end

print FL "Age:32\n"; # Writing the second line in the file followed by a line break

print FL "Gender:Male\n"; # Writing the third line in the file followed by a line break

flock(FL,8); # Releasing the lock from the file

close(FL); # closing the file after writing
After executing the script in the example above and few lines have been written 
in "text.txt" file, the following example shows how to read all the lines from 
the file: 

#!/usr/bin/perl

print "content-type: text/html \n\n"; 

open(FL,"<./test.txt"); # Opening the file in read mode. FL here represents the file handle required and can be any non keyword text

flock(FL,2); # Locking the file for reading

while (!eof(FL)) { # iterating the loop till the end of the file is reached
 chomp($rec=); # fetches the line the file handle is pointing at currently
 print "$rec\n";
}

flock(FL,8); # Releasing the lock from the file

close(FL); # closing the file after writing

Output:
-------------------
|Name:James Dcosta|
|Age:32           |
|Gender:Male      |
-------------------

File opening modes/ entities:
-----------------------------
< read mode
> create and write mode
>> create and append mode
+< read and update mode
+> read and write mode
+>> read and append mode