2008-10-23 17 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 
相关问题