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

Dear Monks,

I have this little script that need to move files around.
It basically works but there is this part where I test if
a directory exists and create it if not.

I'm almost certain that there is a more elegant solution
than the one shown below (except that this will blow up
if the drive does not exists, that is).

Any ideas?

si_lence
use warnings; use strict; my $path="d:/temp/f1/f2/"; my $path_so_far; my @parts = split("/", $path); foreach my $part (@parts) { $path_so_far .= $part ."/"; if ( !(-e $path_so_far) ) { mkdir($path_so_far) || die "not able to mkdir $path_so_far: $! +"; } }

Replies are listed 'Best First'.
Re: make directories from path
by borisz (Canon) on Oct 12, 2004 at 14:38 UTC
    use File::Path; eval { mkpath($path) }; if ($@) { print "Couldn't create $path: $@"; }
    Boris
      I knew there is something like that!
      But somehow I was too blind to see
      Thanks

      si_lence
Re: make directories from path
by pizza_milkshake (Monk) on Oct 12, 2004 at 14:46 UTC
    it looks like you can test for a drive's existence in win32 with Win32::DriveInfo. as for the equivalent of `mkdir -p`, look at use File::Path qw(mkpath);

    perl -e"\$_=qq/nwdd\x7F^n\x7Flm{{llql0}qs\x14/;s/./chr(ord$&^30)/ge;print"

Re: make directories from path
by bpphillips (Friar) on Oct 12, 2004 at 14:47 UTC
    a unix specific example (slashes are different on W32 and not sure about checking for drive's existence)
    perl -e 'my $p; mkdir $_ foreach(grep {!-d} map {$p .= "/$_";} grep {! +m/^$/} split(/\//,$path));
Re: make directories from path
by periapt (Hermit) on Oct 13, 2004 at 12:44 UTC
    A simple, Win32 specific implementation would be to check for the nul file. Every drive and directory has a nul directory associated with it. So to see if a drive/direcotry exists, check to see if the nul file exists.
    print (system("IF EXIST J:/nul exit 1 ELSE exit 0\")) ? 'drive exists' : 'drive does not exist;
    Interestingly enough the perl operator for file existence (-e) doesn't identify the nul file so I guess it is meaningful only to DOS/Win32 OS's

    PJ
    use strict; use warnings; use diagnostics;