codescracker


perl

Perl File I/O



« Previous Tutorial Next Tutorial »


You are free to handle file (file i/o operations) using your perl program.

Open a File in Perl

Here are the two functions used with multiple forms to open any new or existing file in perl:

open FILEHANDLE, EXPR
open FILEHANDLE

sysopen FILEHANDLE, FILENAME, MODE, PERMS
sysopen FILEHANDLE, FILENAME, MODE

Here, the FILEHANDLE is the file handle returned by the function open(), and EXPR is the expression having the file name and mode of opening the file. Here is the general form to open a file named myfile.txt using the function open() in perl.

open(DATA, "<myfile.txt");

Here, DATA represents the file handle which will be used to read the file named myfile.txt here. Here is an example of opening the file myfile.txt in writing mode. To open a file in perl, in writing mode, then use > sign to indicate that the file has to be opened in the writing mode in perl:

open(DATA, ">myfile.txt") or die "Error in opening the file myfile.txt, $!";

Close a File in Perl

Here is the general form to close a file in perl:

close(FILEHANDLE);

Here, FILEHANDLE is the file handle returned by the function open().

Read a File in Perl

Below is an example program, opens a file named myfile.txt and will print its content on the output screen:

#!/usr/bin/perl

open(DATA, "<file.txt") or die "Error in opening the file myfile.txt, $!";

while(<DATA>)
{
   print("$_");
}

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test