user3985999
user3985999

Reputation:

How to copy the folder from one directory to another in perl?

I want to copy the folder from one directory to another.

For Example I have folder in D drive like Sample it that itself contain many folder.I want to copy this sample folder with its sub folders to some other drive.Here i have done something but it copies only the files.

#!/usr/bin/env perl

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

my $source_dir = "aa";
my $target_dir = "bb";

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

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

closedir($DIR);

Please help with this...

Thanks in advance

Upvotes: 2

Views: 5721

Answers (2)

VJ_Bravo
VJ_Bravo

Reputation: 53

use strict;
use warnings;
use File::Copy::Recursive qw(dircopy);
dircopy($source_dir,$target_dir) or die("$!\n");

Upvotes: 2

Borodin
Borodin

Reputation: 126722

You need to use either the File::Copy::Recursive module, which has a number of related functions from which you probably want dircopy; or the File::Mirror module, which has a mirror function that does the same as dircopy, plus a recursive function that allows you to provide a block of code to control exactly how the nodes will be copied.

Upvotes: 4

Related Questions