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 - Open a File


Tutorials Perl

Topic

How to Open a File in Perl programming?



Explanation

To open a file to write or to read data, a "File Handle" is given usually in capital letters, then provide the appropriate "access mode" options like read, read/write, write options and then the filename of the file.

Example:
    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    open(HANDLE,"<file1.txt")or die "can't open file: $!";
    while ($record = <HANDLE>)
    {
      print $record;
     }
    close (HANDLE);
Result:
     qddddddd

In the above example name of the file handle is "HANDLE", we open a file "file1.txt" with read only acess mode, if an error occurs the "die" statement displays a error message. When the file is open all contents of the file is displayed using a while loop.

The user can also use sysopen() instead of open(). If the mode is missing by default the file takes the default mode that is "<" (read only) mode.Using the file handles the user can add any data like array values, hash values, variable's, text etc.

The following is the table of modes that can be used for file handling.

MODE DESCRIPTION
< READ
> WRITE, CREATE, TRUNCATE
>> WRITE, APPEND, CREATE
+< READ, WRITE
+> READ, WRITE, TRUNCATE, CREATE
+>> READ, WRITE, CREATE, APPEND

The following table list the flags that can be used with the sysopen() function

VALUE DESCRIPTION
O_RDWR Read and Write
O_RDONLY Read Only
O_WRONLY Write Only
O_CREAT Create the file
O_APPEND Append the file
O_TRUNC Truncate the file
O_EXCL Stops if file already exists
O_NONBLOCK Non-Blocking usability
Example:
    #! C:\programfiles\perl\bin\perl
    print "content-type: text/html\n\n";
    sysopen(HANDLE,'file1.txt',O_RDONLY)or die "can't open file: $!";
    while ($record = <HANDLE>)
    {
      print $record;
     }
    close(HANDLE);
Result:
    Hscriptssssssssssss

In the above example we have used sysopen(), with the flag "O_RDONLY" which opens file in the read only mode.In the while loop we print the conetents of 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