Perl将文件复制到尚未创建的目标目录树中的最佳方法是什么?Perl中将文件复制到尚未创建的目录树中的最佳方式是什么?
喜欢的东西
copy("test.txt","tardir/dest1/dest2/text.txt");
不会起作用,因为目录tardir/DEST1/dest2还不存在。在Perl中创建目录的最佳方式是什么?
Perl将文件复制到尚未创建的目标目录树中的最佳方法是什么?Perl中将文件复制到尚未创建的目录树中的最佳方式是什么?
喜欢的东西
copy("test.txt","tardir/dest1/dest2/text.txt");
不会起作用,因为目录tardir/DEST1/dest2还不存在。在Perl中创建目录的最佳方式是什么?
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: [email protected]\n" unless $dirs;
}
copy($file,$path) or die "Failed to copy $file: $!\n";
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;
}
File::Copy::Recursive :: FCOPY()是将非主,但结合了文件::路径:: mkpath()和文件复制:: ::复制()解决方案到的东西更短,和蜜饯权限不像File :: Copy。它还包含其他漂亮的实用功能。
参见进行复制的其他答案,但对于创建目录Path::Class是非常好的使用方法:
use Path::Class;
my $destination_file = file('tardir/dest1/dest2/test.txt');
$destination_file->dir->mkpath;
# ... do the copying here
根据corelist文件::自5.001路径一直是核心的一部分。 – 2008-10-23 13:05:42
有趣。它不在5.10中,但它在早期版本中存在。 – 2008-10-23 13:08:22
Corelist是关于版本号的符号的一个小错误。运行“corelist -a File :: Path”,你会看到v2.04是以perl“5.01”(而不是5.010)发布的。 – 2008-10-23 13:10:19