How do I create a directory and parent directories in one Perl command?

余生颓废 提交于 2019-12-18 12:55:32

问题


In Perl, how can I create a subdirectory and, at the same time, create parent directories if they do not exist? Like UNIX's mkdir -p command?


回答1:


use File::Path qw(make_path);
make_path("path/to/sub/directory");

The deprecated mkpath and preferred make_path stemmed from a discussion in Perl 5 Porters thread that's archived here.

In a nutshell, Perl 5.10 testing turned up awkwardness in the argument parsing of the makepath() interface. So it was replaced with a simpler version that took a hash as the final argument to set options for the function.




回答2:


Use mkpath from the File::Path module:

use File::Path qw(mkpath);
mkpath("path/to/sub/directory");



回答3:


Kindly ignore if you are looking for a Perl module with 'mkdir -p' functionality but the following code would work:

my $dir = '/root/example/dir';

system ("mkdir -p $dir 2> /dev/null") == 0 
    or die "failed to create $dir. exiting...\n";

You can use a module but then you have to install it on each server you are going to port your code on. I usually prefer to use system function for a work like mkdir because it's a lesser overhead to import and call a module when I need it only once to create a directory.




回答4:


ref http://perldoc.perl.org/File/Path.html

"The make_path function creates the given directories if they don't exists [sic!] before, much like the Unix command mkdir -p"




回答5:


mkdir() allows you to create directories in your Perl script.

Example:

use strict;
use warnings;

my $directory = "tmp";

unless(mkdir($directory, 0755)) {
        die "Unable to create $directory\n";

This program create a directory called "tmp" with permissions set to 0755 (only the owner has the permission to write to the directory; group members and others can only view files and list the directory contents).



来源:https://stackoverflow.com/questions/1050365/how-do-i-create-a-directory-and-parent-directories-in-one-perl-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!