如何在Perl中一次性创建一个包含所有子目录的路径?

Hai*_*ang 9 perl path

如果您有一个文件的路径(例如,/ home/bob/test/foo.txt),其中路径中的每个子目录可能存在也可能不存在,如何以使用"的方式创建文件foo.txt" /home/bob/test/foo.txt"作为唯一的输入,而不是逐个创建路径中的每个不存在的目录,最后创建foo.txt本身?

set*_*eth 25

您可以使用File :: BasenameFile :: Path

 use strict;
 use File::Basename;
 use File::Path qw/make_path/;

 my $file = "/home/bob/test/foo.txt";
 my $dir = dirname($file);
 make_path($dir);
 open my $fh, '>', $file or die "Ouch: $!\n"; # now go do stuff w/file
Run Code Online (Sandbox Code Playgroud)

我没有添加任何测试来查看该文件是否已经存在但是使用Perl添加非常容易.

  • @Hobbs:检查`File :: Path`的文档.`mkpath`被描述为"legacy",新接口使用`make_path`作为该函数. (2认同)