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

标签 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);

}

最佳答案

我建议您做一些事情:

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

   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

关于Perl 将文件从一个目录复制到另一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41620167/

相关文章:

apache - Perl 库无法在 WampServer 上运行

regex - 匹配空格但不匹配换行符

regex - 在 Perl 中使字符串对正则表达式安全

perl - 删除特定行中的选项卡

mysql - 通过 Perl 脚本将带有断线的 MySQL TEXT 字段转换为 XML 会返回格式错误的符号

arrays - 在 perl 中使用 <$socket[i]> 读取数组中的套接字

perl - 如何使用相同的数据创建多个哈希引用?

perl - 如何在 ubuntu 12.10 上获得 p5-Switch

perl - 如何更改文本文件中的记录分隔符?

mysql - Perl、DBI 和 MySQL 定界符