ディレクトリの階層コピーを行う
先に結論を出すと、UNIX系のシステムでは、
system('cp','-r',$from,$to);
とすると良いでしょう。他の環境では以下のコードが役に立つかも
知れません。
階層コピーのサンプルです。
#!/usr/local/bin/perl
use File::Find;
use File::Copy;
$from = 'tmp'; #コピー元ディレクトリ名
$to = "$ENV{PWD}/aaa"; #コピー先ディレクトリ名(絶対パス)
find(\&wanted, $from);
sub wanted{
local($new) = $File::Find::name;
$new =~ s#^\Q$from\E#$to#; # コピー先ファイル名
if(-d){ # ディレクトリ?
mkdir($new, 0777); # ディレクトリ作成
}else{
copy($_, $new); # ファイルのコピー」
}
}
__END__
速度比較
1つのディレクトリを丸々コピーする2つのスクリプト(1つ
はFile::Findを使うもの、もう一つはcpを使うもの)で
Benchmark.pmに掛けた所、
#Perlの起動を含めて計った場合
Benchmark: timing 20 iterations of cp, perlfind...
cp: 7 secs ( 0.00 usr 0.03 sys + 0.32 cusr 1.09 csys = 1.45 cpu)
perlfind: 13 secs ( 0.02 usr 0.03 sys + 5.80 cusr 2.08 csys = 7.93 cpu)
cpの方が倍近く速かったです。
一旦File::FindやFile::Copyを読み込ませた後でも
#関数の実行だけ計った場合
Benchmark: timing 20 iterations of cp, perlfind...
cp: 5 secs (-0.03 usr 0.08 sys + 0.02 cusr 0.73 csys = 0.80 cpu)
perlfind: 6 secs ( 0.59 usr 1.07 sys + 0.02 cusr 0.12 csys = 1.80 cpu)
cpコマンドの方が若干速そうです。大きいディレクトリの
コピーならもっと差が出るでしょう。