|
下面这段代码拷贝一个目录到另一个目录时,($src ==> $dst)
当源目录有多个子目录的时候,程序执行完毕以后目标目录仅拷贝了一个源目录的子目录,为什么呀?
举个例子:
src_top有三个子目录src_sub[123],执行
$ ./mcp src_top dst_top
之后,dst_top下可能仅有一个src_sub1目录,其余的两个子目录漏掉了,哪位达人解释一下啊?感激不尽!
[PHP]
#!/usr/bin/perl -w
use warnings;
use strict;
my $srcdir;
my @dstdirs;
my $dstdir;
sub copy_file {
my ($infile, $outfile) = @_;
my ($mode) = ();
if(!open (INFILE, $infile)){
warn "unable to open file $infile for reading, error: $!\n";
return -1;
}
($mode) = (stat($infile))[2];
if(!open(OUTFILE, ">$outfile")){
warn "unable to open file $outfile for writing, error: $!\n";
close(INFILE);
return -1;
}
chmod($mode, $outfile);
while(defined(($_ = <INFILE>))){
print OUTFILE $_;
}
close(OUTFILE);
close(INFILE);
return 0;
}
sub copy_dir {
my ($src, $dst) = @_;
my ($mode) = ();
my ($infile, $outfile) = ();
my ($srcpath, $dstpath) = ();
if(!opendir(IND, $src)){
warn "unable to open directory $src for reading, error: $!\n";
return -1;
}
($mode) = (stat($src))[2];
if(! -d $dst){
if(!mkdir($dst, $mode & 0777)){
warn "unable to create directory $dst, error: $!\n";
return -1;
}
}
while(defined($infile = readdir(IND))){
if($infile eq "." || $infile eq ".."){
next;
}
$srcpath = sprintf("%s/%s", $src, $infile);
$dstpath = sprintf("%s/%s", $dst, $infile);
if(-f $srcpath){
copy_file($srcpath, $dstpath);
} elsif(-d $srcpath){
copy_dir($srcpath, $dstpath);
} else {
warn "skiping non-regular file $srcpath\n";
}
}
close(IND);
return 0;
}
if($#ARGV + 1 < 2){
die "*** usage: mcp srcdir tgdir1 tgdir2 ... tgdirn ***\n";
}
($srcdir, @dstdirs) = @ARGV;
foreach $dstdir (@dstdirs){
copy_dir($srcdir, $dstdir);
}
[/PHP] |
|