Tuesday, June 26, 2012

Perl - Reading, Writing , Appending & Closing file

You cannot read and write a file at the same time. You have to tell Perl in the Open statement which of the three modes (reading , writing , or appending) .

In Perl version 4 and 5  perl looks at the first character or two filename you give it and determines the open mode from that.

To read the file: Precede the name with <.

To write a file: Precede with the name >.

To append to a file: Precede the name with >>.

 Syntax for the statement is:
open(HANDLE, MODE , FILENAME)

Example:
Open(INFILE, '<sample.txt'); # for reading
Open(INFILE, '>sample.txt'); # for writing
Open(INFILE , '>>sample.txt) # for appending
$file = '>sample.txt'; # Prepare for writing
    
Closing the file name    
When you are done with reading or writing to a file handle, you need to close it. Perl closes all your file handles for you. To close the file handle, use the close function like this:

close FILE;  

No comments:

Post a Comment