1.6.2 Copying a File

Now, we write a program that copies contents of one text file into another. Copying a file involves reading from a file and writing to another file. So, we need two filehandles, one for the file from which the program reads and another for the file into which the program writes.

Program 1.10

#!/usr/bin/perl
#file copy1.pl
#copying everything from one file to another

use strict; 
my ($oldfilename, $newfilename);

print "Please give me a file name >> ";
$oldfilename = ;
chomp ($oldfilename);
$newfilename = $oldfilename . ".new";

open (IN, $oldfilename);
open (OUT, ">$newfilename");

while (){
    print OUT $_;
}

close (IN);
close (OUT);

print "File `$newfilename' is an exact copy of file `$oldfilename'\n";

The program prompts the user for the name of the file to copy. The name of the file to copy is stored in the variable $oldfilename. The name of the file is a string. Next, the program creates a name for the file into which the copying will be done. The name of the new file is obtained by concatenating .new to the name of the file entered by the user. In Perl, string concatenation is done by using the dot (.) operator.

The program opens a filehandle called IN for reading the contents of the file whose name is entered by the user. The program also creates another filehandle OUT for writing purposes. To open a filehandle for writing, the second argument to open must have the name of the file preceded by >. When a file is opened for writing, the file is created if the file does not exist and the user has permission to create/write files. If the file already exists and the user has permission to write into the file, the file is overwritten. Note permissions are usually an issue only in Unix systems.

The while loop simply reads a line of text from the IN filehandle and prints it out to the OUT filehandle. Printing the line to the OUT filehandle causes the line to be written into the new file.