Perl 中将文件复制到尚未创建的目录树的最佳方法是什么?

发布于 2024-07-07 09:05:46 字数 210 浏览 7 评论 0原文

在 Perl 中将文件复制到尚未创建的目标目录树的最佳方法是什么?

类似的东西

copy("test.txt","tardir/dest1/dest2/text.txt");

不会工作,因为目录 tardir/dest1/dest2 还不存在。 在 Perl 中创建目录进行复制的最佳方法是什么?

What is the best way in Perl to copy files to a yet-to-be-created destination directory tree?

Something like

copy("test.txt","tardir/dest1/dest2/text.txt");

won't work since the directory tardir/dest1/dest2 does not yet exist. What is the best way to copy with directory creation in Perl?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

聽兲甴掵 2024-07-14 09:05:46
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";
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";
滿滿的愛 2024-07-14 09:05:46
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;
}
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;
}
琴流音 2024-07-14 09:05:46

File::Copy::Recursive::fcopy() 不是-core 但将 File::Path::mkpath() 和 File::Copy::copy() 解决方案组合成更短的内容,并保留与 File::Copy 不同的权限。 它还包含其他漂亮的实用功能。

File::Copy::Recursive::fcopy() is non-core but combines the File::Path::mkpath() and File::Copy::copy() solution into something even shorter, and preserves permissions unlike File::Copy. It also contains other nifty utility functions.

空城缀染半城烟沙 2024-07-14 09:05:46

请参阅其他答案以进行复制,但要创建目录 Path::Class 非常好用:

use Path::Class;

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

# ... do the copying here

See the other answers for doing the copying, but for creating the directory Path::Class is very nice to use:

use Path::Class;

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

# ... do the copying here
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文