mkdir -p in Perl

jdavidb on 2004-07-20T17:15:14

The equivalent of mkdir -p in Perl is:

use File::Path qw(mkpath);
mkpath $directory;


Misnamed

jdavidb on 2004-07-20T17:16:21

On that note, I submit that File::Path is misnamed. The summary of the module is given as "create or remove directory trees." In other words, it's mkdir -p and rm -rf in Perl.

Convenient to have, hard to find.

Re:Misnamed

acme on 2004-08-18T11:45:11

It is a very useful module. However, the naming is a bit screwy. If it's called File::Path, why does it have mkpath() and rmtree(). Surely it should be rmpath() in that case?

Anyway, it's another handy core module that people don't notice because of the name, sigh.

Omission

Dom2 on 2004-07-20T21:09:32

You left off a bit:
... or die "mkpath: Boom!";

Re:Omission

jplindstrom on 2004-07-21T04:20:43

Actually you most often don't care whether you could create the directory structure, you care whether it's there after the call. So it's:
mkpath($directory);
-d $directory or die("Could not create ($directory)");
Conversely, if you actually want to create the directory, often the real intent is to make sure it's newly created. So delete it first, then create it.
rmtree($directory);
-d $directory and die("Could not remove ($directory)");
 
mkpath($directory);
-d $directory or die("Could not create ($directory)");

Re:Omission

jdavidb on 2004-07-21T14:31:34

In the case of rmtree, perhaps the test should be -e, not -d. I believe your test would fail if the file existed and was not a directory. (Could be wrong.)

Re:Omission

jdavidb on 2004-07-21T14:30:27

The reason I did not do this is it doesn't work. mkpath returns a list of the directories created, not a success or failure. And if you run the program a second time, you get back an empty list (false) because the directory is already created.

I like jplindstrom's approach, although in my case I immediately execute a chdir or die, which has more or less the same effect.