[英]How can I recursively copy the contents of directory using Perl?
I am running the current version of ActivePerl on Windows Vista, and I was wondering if you could show me the best and simplest way to copy a folder and it's contents to another location. 我在Windows Vista上运行当前版本的ActivePerl ,我想知道您是否可以向我展示将文件夹及其内容复制到另一个位置的最佳和最简单的方法。 Contents would include various files, and most likely some more nested folders.
内容将包括各种文件,并且很可能包含一些嵌套文件夹。
I imagine there must be a module out there somewhere that I don't know about that does this - but if there is a simple homebrew type of solution I'd like to see that also. 我想在那里必定有一个我不知道的模块就是这样 - 但如果有一个简单的自制类型的解决方案,我也希望看到它。
If you are simply copying and not doing any processing on the files, there is no reason not to use xcopy
. 如果您只是复制而不对文件进行任何处理,则没有理由不使用
xcopy
。
Now, I wrote the script below in light of Telemachus's comments to provide you with a starting point. 现在,我根据Telemachus的评论编写了下面的脚本,为您提供了一个起点。 I personally would stick with
xcopy
for copying and File::Find
if file contents need to be processed. 我个人会坚持使用
xcopy
进行复制,而File::Find
是否需要处理文件内容。 Besides, I am sure there are about 37 bugs in the code below. 此外,我相信下面的代码中有大约37个错误。 But, if you want to play around, it might be instructive:
但是,如果你想玩,它可能是有益的:
#!/usr/bin/perl
use strict;
use warnings;
use File::Spec::Functions qw( catfile );
die "mydeepcp src-dir target-dir\n" unless @ARGV == 2;
my ($src, $target) = @ARGV;
mydeepcp( $src => $target );
sub mydeepcp {
my ($src, $target) = @_;
opendir my $dir_h, $src
or die "Cannot open directory: '$src': $!";
while ( my $file = readdir $dir_h ) {
next if $file =~ m{^\.\.?$};
my $src_path = catfile $src => $file;
my $target_path = catfile $target => $file;
if ( -d $src_path ) {
# FIXME: insert code somewhere to create destination dir
mydeepcp($src_path => $target_path);
}
elsif ( -f _ ) {
if ( my $err = docp($src_path => $target_path) ) {
warn sprintf(
"Error copying '%s' from '%s' to '%s': %s\n",
$file, $src, $target, $err
);
}
}
else {
warn "Skipping '$src_path'\n";
}
}
closedir $dir_h;
return;
}
sub docp {
my ($src, $target) = @_;
warn "'$src' => '$target'\n";
return;
}
__END__
Output: 输出:
C:\Temp> ghj c:\windows f:\qwert
...
'C:\windows\$hf_mig$\KB899591\update\spcustom.dll' => 'F:\qwert\$hf_mig$\KB899591\update\spcustom.dll'
'C:\windows\$hf_mig$\KB899591\update\update.exe' => 'F:\qwert\$hf_mig$\KB899591\update\update.exe'
'C:\windows\$hf_mig$\KB899591\update\update.ver' => 'F:\qwert\$hf_mig$\KB899591\update\update.ver'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.