2008-10-23 18 views

回答

27
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"; 
8
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; 
} 
+0

根據corelist文件::自5.001路徑一直是核心的一部分。 – 2008-10-23 13:05:42

+0

有趣。它不在5.10中,但它在早期版本中存在。 – 2008-10-23 13:08:22

+0

Corelist是關於版本號的符號的一個小錯誤。運行「corelist -a File :: Path」,你會看到v2.04是以perl「5.01」(而不是5.010)發佈的。 – 2008-10-23 13:10:19

5

File::Copy::Recursive :: FCOPY()是將非主,但結合了文件::路徑:: mkpath()和文件複製:: ::複製()解決方案到的東西更短,和蜜餞權限不像File :: Copy。它還包含其他漂亮的實用功能。

1

參見進行復制的其他答案,但對於創建目錄Path::Class是非常好的使用方法:

use Path::Class; 

my $destination_file = file('tardir/dest1/dest2/test.txt'); 
$destination_file->dir->mkpath; 

# ... do the copying here 
相關問題