6.11.2 Copying Files Recursively: File::NCopy Module
6.11.2 Copying Files Recursively: File::NCopy Module
Sometimes, it is necessary to copy files and directories recursively. It can be done with not much difficulty following the discussion earlier in the chapter, either recursively or non-recursively. There is a module called File::NCopy that makes recursive copying of files and directories really easy. The following program shows the use of File::NCopy.
Program 6.18
#!/usr/bin/perl
#file ncopy.pl
use File::NCopy;
#non-recursive copying
$f = File::NCopy->new();
$f->copy ("jk1.jpg", "jk3.jpg");
$f->copy("jk1.jpg", "aa");
$f->copy("jk1.jpg", "aa/jk4.jpg");
$f->copy("a", "aa");
#recursive copying
$f = File::NCopy->new('recursive' => 1);
$f->copy("a", "aa");
The module’s functions or methods can be called using a functional interface as well as an object interface. We discuss the object interface here. To start copying, we create a new instance of a File::NCopy object. The first instance of the File::NCopy object can copy only non-recursively because no options were given to the new method.
The first copy method call copies the file jk1.jpg to jk3.jpg. The second call copies the file jk1.jpg into the directory aa. The third call copies the file jk1.jpg into the directory aa with the name jk4.jpg. The fourth call copies the directory a into the directory aa. A recursive listing of the a directory, at this time, shows
the following.
a:
b/
a/b:
c/
a/b/c:
jk1.jpg mkdir.pl*
So, there is a directory b under a, and a directory c under a/b and two files in the a/b/c directory. However, the fourth call to copy does not copy anything into the aa directory because the copy is not done recursively. To perform a recursive copying, we need to make the
File::NCopy object recursive as shown in the following declaration.
$f = File::NCopy->new('recursive' => 1);
After this call to new, the following call to copy copies the directory a recursively into the director aa.
$f->copy("a", "aa");
Now, a recursive listing of the directory aa show the following.
aa:
a/ jk1.jpg jk4.jpg
aa/a:
b/
aa/a/b:
c/
aa/a/b/c:
jk1.jpg mkdir.pl*
