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