user3781528
user3781528

Reputation: 639

Perl copying files from one directory to another

I'm trying to copy files from multiple directories with the code bellow. It prints out the correct path and files but fails to copy them. Please suggest how to fix this issue? Thanks

#!/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);

}

Upvotes: 2

Views: 9942

Answers (1)

carlosn
carlosn

Reputation: 433

There are a few things I would recommend you to do:

Close your file handles as soon as possible if you are not using it anymore:

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

As you are trying to backup some files and directories maybe the target destination will not have the directory so:

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

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

And the last one:

   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: $!";
         }


      }
   }

Always TIMTOWTD, you could use File::Find which has a simple tutorial here.

Upvotes: 2

Related Questions