Perl将文件从一个目录复制到另一个目录

时间:2017-01-12 18:13:42

标签: perl

我尝试使用下面的代码从多个目录中复制文件。它打印出正确的路径和文件,但无法复制它们。请建议如何解决此问题?感谢

#!/usr/bin/perl

use strict;
use warnings;
use File::Copy;

my $target_dir = "";

my @dirs = grep { -d } glob '/data/results/*';

for my $source_dir ( @dirs ) {

   opendir(my $DIR, $source_dir) || die "can't opendir $source_dir: $!";  
   my @files = readdir($DIR);

   print "the directory is $source_dir\n";
    my $run_folder = (split '/', $source_dir)[3];
    print "the folder is $run_folder\n";

   $target_dir = "/data/backup/$run_folder";
   print $target_dir;

   foreach my $t (@files)
   {
      if(-f "$source_dir/$t" ) {
         #Check with -f only for files (no directories)
         print "$source_dir/$t";
         print "$target_dir/$t";

         copy "$source_dir/$t", "$target_dir/$t";
      }
   }

   closedir($DIR);

}

1 个答案:

答案 0 :(得分:0)

我建议你做一些事情:

如果您不再使用它,请尽快关闭文件句柄:

   opendir(my $DIR, $source_dir) || die "can't opendir $source_dir: $!";  
   my @files = readdir($DIR);
   close ($DIR);

当您尝试备份某些文件和目录时,目标目标可能没有目录:

 $target_dir = "/data/backup/$run_folder"; 
 print $target_dir;

 if ( ! -d $target_dir ) 
 { 
   #creates the dir
 }

最后一个:

   foreach my $t (@files)
   {
      chomp $t; # it removes any new line
      if(-f "$source_dir/$t" ) {
         #Check with -f only for files (no directories)
         print "$source_dir/$t";
         print "$target_dir/$t";

         if ( ! copy "$source_dir/$t", "$target_dir/$t" )
         {
            print "Some error: $!";
         }


      }
   }

总是TIMTOWTD,你可以使用File :: Find,它有一个简单的教程here