Perl Topics





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
Perl Tutorial
Introduction Introduction
Installing Perl Installing Perl
Basics of Perl Basics of Perl
Scalar Variables Scalar Variables
Operators Operators
Control Structures Control Structures
Lists Lists
Array Array
Arrays Manipulation Arrays Manipulation
Arrays Functons Array Functions
Hash Hash
Hash Functions Hash Functions
String Functions String Functions
Regular Expression Regular Expression
Regular Expression Functions Regular Expression Functions
Numerical Functions Numerical Functions
List Functions List Functions
User Defined Function User Defined Function
File Handling File Handling
Forums Ask Your Doubts
Feedback Feedback
 





Perl File Handling - Writing & Appending into a File


Tutorials Perl

Topic

How to Write into a File in Perl programming?



Explanation

To write data into a file only if the "access mode" for the file should be in write or read/write modes. The access modes to write into a file can be among the following ">, +>,+<".

Example:
    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    open(HANDLE,"+>file1.txt")or die "can't open file:$!";
    print HANDLE "HScripts!";
    close(HANDLE);
Result in "file1.txt":
    HScripts!

In the above example we open "file1.txt" in the write mode, along with a "die" statement to display error if the file doesn't have the "write" permission. A string is printed into the file, then the handle is closed. When the "file1.txt" is opened it will have the text "Hscripts!" printed into the file.

Appending a file:

To write data to an existing file, one can open the file to which data need to updated in the append mode ">>", then can append the required data.

Example:
    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    open(HANDLE,">>file1.txt")or die "can't open file:$!";
    print HANDLE "HScripts is gone!";
    close(HANDLE);
Result as in "file1.txt":
    HScripts!HScripts is gone!

In the above example the file "file1.txt" already has the text "Hscripts!", make sure file1.txt is saved and closed. Now we open the same file in the append mode ">>" then the text "Hscripts is gone!" is printed into the file.






A Note
Simple introduction, basic CGI perl programming codes with examples. Do send your feedback or suggestions on this tutorial. This is a copyright content.

Other Links

web hosting