Chr*_*s N 20 directory perl copy
Perl将文件复制到尚未创建的目标目录树的最佳方法是什么?
就像是
copy("test.txt","tardir/dest1/dest2/text.txt");
Run Code Online (Sandbox Code Playgroud)
由于目录tardir/dest1/dest2尚不存在,因此无法正常工作.在Perl中使用目录创建进行复制的最佳方法是什么?
Rob*_*ble 30
use File::Path;
use File::Copy;
my $path = "tardir/dest1/dest2/";
my $file = "test.txt";
if (! -d $path)
{
my $dirs = eval { mkpath($path) };
die "Failed to create $path: $@\n" unless $dirs;
}
copy($file,$path) or die "Failed to copy $file: $!\n";
Run Code Online (Sandbox Code Playgroud)
use File::Basename qw/dirname/;
use File::Copy;
sub mkdir_recursive {
my $path = shift;
mkdir_recursive(dirname($path)) if not -d dirname($path);
mkdir $path or die "Could not make dir $path: $!" if not -d $path;
return;
}
sub mkdir_and_copy {
my ($from, $to) = @_;
mkdir_recursive(dirname($to));
copy($from, $to) or die "Couldn't copy: $!";
return;
}
Run Code Online (Sandbox Code Playgroud)
File :: Copy :: Recursive :: fcopy()是非核心的,但将File :: Path :: mkpath()和File :: Copy :: copy()解决方案组合成更短的内容,并保留了与File不同的权限: :复制.它还包含其他漂亮的实用功能.