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?
A parent directory is a directory that is above another directory in the directory tree. To create parent directories, use the -p option. When the -p option is used, the command creates the directory only if it doesn't exist.
Building a structure with multiple subdirectories using mkdir requires adding the -p option. This makes sure that mkdir adds any missing parent directories in the process.
Perl Articlesmkdir() allows you to create directories in your Perl script. The following program creates a directory called "temp". use strict; use warnings; sub main { my $directory = "temp"; unless(mkdir $directory) { die "Unable to create $directory\n"; } } main();
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.
Use mkpath from the File::Path module:
use File::Path qw(mkpath);
mkpath("path/to/sub/directory");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With