| Search perlmeme.org | |
| Home » Faqs » System » Rcopy |
You want to to copy a directory (and all the files and subdirectories in it), from your Perl program.
You want functionality equivalent to the recursive copying performed by the Unix "cp -R" command, but you don't want to use a system() call to do this.
Use the File::NCopy module to recursively copy a directory and all it's contents.
#!/usr/bin/perl
use strict;
use warnings;
use File::NCopy;
my $source_dir = 'aa';
my $target_dir = 'bb';
mkdir($target_dir) or die "Could not mkdir $target_dir: $!";
my $cp = File::NCopy->new(recursive => 1);
$cp->copy("$source_dir/*", $target_dir)
or die "Could not perform rcopy of $source_dir to $target_dir: $!";
If you're familiar with the Unix copy command cp, you might be
excused for thinking that you could simply copy the existing source directory
to a brand new target directory as follows:
$cp->copy($source_dir, $target_dir); /* This will fail
Instead you have to first create the target directory with the mkdir
function, and then supply the source argument with the trailing * wildcard,
in order to get the desired behaviour:
$cp->copy("$source_dir/*", $target_dir) ....
perldoc File::Copy