Perl Operators   «Prev  Next»
Lesson 14I/O operators
Objective Use I/O operators to work with files in a Perl script.

Perl Input Output Operators

Perl has some special operators for dealing with files. These operators make it particularly easy to work with files in Perl. There are three common file actions with which you will want to use these operators:
  • Opening a file in Perl You can open a file with one of these forms of the
    open

    function:
    # opens file $filename for input
    open(HANDLE, "<$filename");
    
    # opens file $filename for
    # output (replaces file)
    open(HANDLE, ">$filename");
    
    # opens file $filename for
    # output (appends to file)
    open(HANDLE, ">>$filename"); 
    
    # opens file $filename for input
    # and output (file must exist)
    open(HANDLE, "+<$filename"); 
    
    # opens file $filename for input 
    # and output (replaces file)
    open(HANDLE, "+>$filename"); 
    

    When you are done with the file, the close function:
    close HANDLE
    

    is used to free up the resources that are used by having the file open.


File Description in Perl

A file is a series of bytes stored on a disk instead of inside the computer's memory. A file is good for long-term storage of information. Information in the computer's memory is lost when the computer is turned off. Information on a disk, however, is persistent. It will be there when the computer is turned back on. We already know how to create a file using a text editor program. In this chapter, you'll see how to manipulate files with Perl. There are four basic operations that you can do with files. You can open them, read from them, write to them, and close them. Opening a file creates a connection between your program and the location on the disk where the file is stored. Closing a file shuts down that connection.
Every file has a unique fully qualified name so that it can't be confused with other files. The fully qualified name includes the name of the disk, the directory, and the file name. Files in different directories can have the same name because the operating system considers the directory name to be a part of the file name. Here are some fully qualified file names:
c:/windows/command/scandisk.ini
c:/a_long_directory_name/a_long_subdirectory_name/a_long_file_name.doc

Caution: You may be curious to know if spaces can be used inside file names. Yes, they can. But, if you use spaces, you need to surround the file name with quotes when referring to it from a DOS or UNIX command line. Note It is very important that you check for errors when dealing with files. To simplify the examples in this module, little error checking will be used in the example.

Reading a Perl File

On a Windows OS, you cannot use a pipe to a Perl program if you call the program from an association.
In other words, this will not work:
You can read an entire file into an array like this:
type foo.txt | test.pl

But this will:
type foo.txt | c:\perl\bin\perl test.pl

@array = <FILEHANDLE>

Or, just one line from a file like this:
$scalar = <FILEHANDLE>

Or you can use the special form of the
while

loop for reading a file. This will put each line of the file in the special $_ variable:
while(<FILEHANDLE>) {
  # $_ has the current line of the file
  }


For example, this program opens a file and prints its contents to the console (just like
cat
in Unix or
TYPE
in DOS):
#!/usr/bin/perl -w

$filename = shift;
open(HANDLE, "<$filename")
 or die "$filename: $!\n";
while(<HANDLE>) { print }
close HANDLE;

The die function is often used for an error exit. It exits and prints a message. The special variable $! contains the last error message from the operating system. There is also special empty filehandle <> that can be used in this circumstance. It will automatically open and read any files which are listed on the command line; or if there are not any, it will use the standard input stream (usually the keyboard or a pipe from another program). That allows you to write the above program like this:
#!/usr/bin/perl -w
while(<>) 
{ 
print 
}
Advanced Perl Programming

Writing a file in Perl

You can write to a file with print by specifying the file handle without a comma before the arguments to print:
print FILEHANDLE "This and that to print\n";

This also works with Perl's C-like printf function:
printf FILEHANDLE "%d%c", 42, 0x0a;

For example, this program will copy the input to a file called output.txt:
#!/usr/bin/perl -w
$outfile = "output.txt";
open(OUTFILE, ">$outfile")
 or die "can't create $outfile: $!\n";
while(<>) { print OUTFILE }
close OUTFILE;

We have just introduced the concept of a Directory Handle for referring to a Directory on disk. We now introduce a similar concept of File Handle for referring to a File on disk from which we can read data and to which we can write data. Similar ideas of opening and closing the files exist. You use the open() operator to open a file (for reading):
open(FILEHANDLE,"file_on_device");
To open a file for writing you must use the ``>'' symbol in the open() operator:
open(FILEHANDLE,">outfile");


Write always starts writing to file at the start of the file. If the file already exists and contains data. The file will be opened and the data overwritten. To open a file for appending you must use the ``>>'' symbol in the open() operator:
open(FILEHANDLE,">>appendfile");

The close() operator closes a file handle:
close(FILEHANDLE);

To read from a file you simply use the <FILEHANDLE> command which reads one line at a time from a FILEHANDLE and stores it in a special Perl variable $_. For example, read.pl:
open(FILE,"myfile")
|| die "cannot open file";
while(<FILE>)
{ print $_; # echo line read
}
close(FILE);

To write to a file you use the Print command and simply refer to the FILEHANDLE before you format the output string via:
print FILEHANDLE "Output String\n";

Therefore to read from one file infile and copy line by line to another outfile we could do readwrite.pl:


Reading an Array from the Standard Input File

In the programs you have seen so far, single lines of input are read from the standard input file and stored in scalar variables. For example:
$var = <STDIN>;

In this case, every appearance of <STDIN> means that another line of input is obtained from the standard input file. Perl also provides a quicker approach: If you assign <STDIN> to an array variable instead of a scalar variable, the Perl interpreter reads in all of the data from the standard input file at once and assigns it. For example, the statement
@array = <STDIN>;

reads everything typed in and assigns it all to the array variable @array. The variable @array now contains a list; each element of the list is a line of input.

Perl Read Write - Exercise

Click the Exercise link below to create a Perl script that uses I/O operators to read one file and write it to another.
Perl Read Write - Exercise

SEMrush Software