amulcahy has asked for the wisdom of the Perl Monks concerning the following question:

Hello All,
How do I test for a directory structures existence and if it does not exist, create it?
e.g.
Test for the structure dir1/dir2/dir3
if it exists, create the file 'filename.txt' in the directry dir1/dir2/dir3.
The initial code I used was:
$fileName = "dir1/dir2/dir3/filename.txt"; open (LIST, ">$fileName");.....
This works if the directory already exists, but does not work without the directories.
I've looked at the manuals but have not been able to find the answer?
Any help would be appreciated.

Thank you

Replies are listed 'Best First'.
Re: file creation
by mirod (Canon) on Jan 31, 2002 at 13:07 UTC

    Well, it will work if the directory structure exists, so you will have to write something like:

    #!/bin/perl -w use strict; my $fileName = "dir1/dir2/dir3/filename.txt"; create_dirs( $fileName); open (LIST, ">$fileName"); sub create_dirs { my $filename= shift; my $dir; while( $filename=~ m{(/?[^/]+)(?=/)}g) { $dir .= $1; next if( -d $dir); mkdir( $dir) or die "cannot create $dir: $!"; } }
      Expanding on your idea and employing File::Spec to provide more friendly cross-platform execution of the subroutine ...

      sub create_dirs { use File::Spec; my $file = shift; my $dir; foreach ( File::Spec->splitdir( (File::Spec->splitpath( $file ))[1 +] ) ) { $dir = File::Spec->catdir($dir, $_); next if -d $dir; mkdir( $dir ) || die $!; } }

       

      perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

      Or:

      use File::Path; mkpath('/dir1/dir2/dir3/');

      gav^

(crazyinsomniac) Re: file creation
by crazyinsomniac (Prior) on Feb 01, 2002 at 09:22 UTC