6.11.1 Copying Files: File::Copy Module
6.11.1 Copying Files: File::Copy Module
The File::Copy module makes copying and moving of files easy. Perl does not have a built-in function to copy files. We have a copying program in Section 1.6.2. In that program, we opened filehandles and read from one file and copied to the other. It is simple, but still a chore.
The following program uses the copy method of the File::Copy module to make a copy of a file.
Program 6.17
#!/usr/bin/perl
#file filecopy.pl
use File::Copy;
use strict;
my ($src, $dest) = @ARGV;
if (!$src or !$dest){
print "Usage: filecopy sourcefile destfile\n";
exit 1;
}
File::Copy::copy ($src, $dest) or die "Cannot copy $src to $dest: $!";
This program takes two arguments: the file to be copied and the name of the copy. If two arguments are not provided, the program exits with an error. Otherwise, it simply copies the file corresponding to the source to the destination. We use the fully qualified name of the copy function to make explicit its source. The following is a call to filecopy.pl
%filecopy.pl mkdir.pl mkdir1.pl
If the directory where the program is running is such that the user has permission to write, the program simply copies the file mkdir.pl to new file mkdir1.pl.
The File::Copy module also provides a method called move to rename a file, i.e., move a file to a new location. Its usage is exactly the same as that of copy. Here we use a functional interface to call a method of the module.
The two file names specified in calls to copy or move can be in directories different from where the program is situated. Of course, the original file has to exist for us to be able to copy from it. In addition, the directory into which the file is being copied or moved also must exist. A program cannot copy into a non-existent directory. It does not create the directory if it does not exist. For example, the following call gives an error.
%filecopy.pl mkdir.pl a/b/mkdir.pl
Cannot copy mkdir.pl to a/b/mkdir.pl:
No such file or directory at filecopy.pl line 11.
If we want to copy in such a case, we will have to parse the destination file name, obtain the path for the file, create the directories in the path, and then copy or move the file.
