can anyone suggest how I can find files in directories and subdirectories and copy them into a new directory.I tried the following code but it doesnot do the job.
- $inputfile1 = "file_index.txt";
-
open(INP1, $inputfile1 ) || die("cannot open $inputfile1 in MAIN");
-
-
@names = <INP1>;
-
close(INP1);
-
-
foreach my $ref (@names)
-
{
-
chomp($ref);
-
-
use File::Find;
-
-
my $localdir = 'C:\Data\reference_material\perl_scripts\copy\test_dataset';
-
-
find(
-
sub {
-
push @files,$File::Find::name,if /$ref/
-
# print $File::Find::name, "\n" if /\.txt$/
-
-
},
-
$localdir);
-
-
}
-
-
foreach my $ref (@files)
-
{
-
chomp($ref);
-
-
my $source_dir=$ref;
-
use File::NCopy;
-
my $target_dir = 'test1';
-
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: $!";
-
-
}
I could point out three problematic area in your code:
1. loading module within the foreach loop. A good programming practice is to load all the modules at the beginning of script unless you have a specific purpose to do otherwise.
2. Declaration of new $cp object within foreach loop with 'my' scope modifier.
-
my $cp = File::NCopy->new(recursive => 1);
-
In this case, $cp object will be created afresh with each iteration of loop that is not what you want.
3. The arguments for copy function should be either both directories or both files. It can't be a combination of this.
Also, if you search in CPAN, you will know that usage of File::NCopy module is deprecated and use of File::Copy::Recursive is suggested.
If all you want is to search for files in folder & subfolders in source directory and copy them to destination directory, the following modified code will do the job.
-
use strict;
-
use File::Find;
-
use File::NCopy qw(copy);
-
-
my $inputfile1 = "file_index.txt";
-
my @files=();
-
open(INP1, $inputfile1 ) || die("cannot open $inputfile1 in MAIN");
-
-
my @names = <INP1>;
-
close(INP1);
-
-
foreach my $ref (@names)
-
{
-
chomp($ref);
-
-
-
my $localdir = 'C:/Data';
-
-
find(
-
sub {
-
push @files,$File::Find::name if(/$ref/);
-
# print $File::Find::name, "\n" if /\.txt$/
-
-
},
-
$localdir);
-
-
}
-
-
-
my $target_dir = 'test1';
-
unless(-e $target_dir) {
-
mkdir($target_dir) or die "Could not mkdir $target_dir: $!";
-
}
-
my $cp = File::NCopy->new(recursive => 1);
-
foreach my $ref (@files)
-
{
-
my $file;
-
chomp($ref);
-
if($ref=~/^.*?\/([^\/]+)$/) { $file=$1; }
-
my $source_dir=$ref;
-
if(-f $source_dir) { ##check if source is file
-
my $target = $target_dir."/".$file;
-
$cp->copy ("$source_dir", "$target") or warn "Could not perform rcopy of $source_dir to $target: $!";
-
}
-
}
-
-