| [reply] |
Path::Class is also capable of this, if you prefer an OO interface. See its documentation on the $dir->mkpath method.
use Path::Class qw(dir);
dir("foo", "bar")->mkpath;
| [reply] [d/l] [select] |
There is the File::Path module (in the standard distribution of Perl even), which does exactly that, create intermediate directories if they don't exist.
| [reply] |
However, be aware that File::Path does not play nice with taint. I had to 'roll my own' in-house equivalent because of this.
| [reply] |
system( "mkdir -p $dirname" );
| [reply] [d/l] |
What about platforms that do not have mkdir? Why rely on external tools at all? That just creates a useless dependency that can't be satisfied on all platforms.
| [reply] [d/l] |
Might be a little heavier that you want, but File::Flat also does this, or rather it lets you just write a file somewhere and it sorts all the details out for you.
File::Flat->write( '/some/path/that/might/exist.txt', $contents );
Of course, the neatest thing is that this...
File::Flat->canWrite( '/some/path/that/might/exist.txt' );
... also "means what you think", that is, "Can I write to the file, or create the file, or create as many directories as are needed".
Great for writing installer-type applications.
| [reply] [d/l] [select] |
$path =~ s[/][\\]g;
system "md $path";
| [reply] [d/l] |
#Note this is windows centric
use strict;
make_dir("c\:\\this\\is\\a\\deep\\subdirectory\\");
sub make_dir {
my ($inpath) = @_; #Full directory path
my $path = ""; #Storage path
#Loop through the sections
foreach(split/\\/,$inpath) {
#Add to path
$path .= $_ . "\\";
#Elimnate the drive and check to see if path exists
if(!/\:/ and !-e $path) {
#If not then make it
mkdir $path;
#Show status for demo
print "Makeing $path\n";
}
}
}
| [reply] [d/l] |
Just emulate the Linux function:
sub MkDirs ($) {
my ($Dir) = @_;
my @Folders = split(/\\|\//, $Dir);
$Dir = shift @Folders;
foreach my $Folder (@Folders) {
$Dir = File::Spec->catfile( $Dir, $Folder );
mkdir $Dir unless (-e $Dir);
}
}
| [reply] [d/l] |
the easiest way with native Perl
sub mkdirp($) {
my $dir = shift;
return if (-d $dir);
mkdirp(dirname($dir));
mkdir $dir;
}
| [reply] [d/l] |