Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Avoiding making a directory that already exists

by Anonymous Monk
on Aug 19, 2001 at 21:23 UTC ( [id://106039] : perlquestion . print w/replies, xml ) Need Help??

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

mkdir "$directory/$month/$day", 0755;
what's a better way to write this so that every time I run the script it isn't trying to create a directory that's already there..... I have this code in a subroutine. I was thinking maybe a if (-e ....... help?

Replies are listed 'Best First'.
Re: Avoiding making a directory that already exists
by VSarkiss (Monsignor) on Aug 19, 2001 at 22:07 UTC
      this is what I needed :) thx
Re: Avoiding making a directory that already exists
by Rudif (Hermit) on Aug 19, 2001 at 23:38 UTC
    Actually, mkpath does the testing for you and will not try to create a directory that is already there. I would not bother to test.
    From Path.pm:

    sub mkpath { my($paths, $verbose, $mode) = @_; ... foreach $path (@$paths) { ... next if -d $path; ... my $parent = File::Basename::dirname($path); unless (-d $parent or $path eq $parent) { push(@created,mkpath($parent, $verbose, $mode)); } ...
    Rudif
Re: Avoiding making a directory that already exists
by scain (Curate) on Aug 19, 2001 at 22:05 UTC
    Well, you haven't given us much to go on, but it sounds like you have the right idea:
    my $newdir = "$directory\/$month\/$day" if (!(-e $newdir)) { mkdir $newdir, 0755 or die "couldn't mkdir $newdir because: $!\n"; }
    Scott

    updated per tilly's suggestion.

      Please add $! to the error check. Very often knowing what the operating system thinks is wrong can make your life much, much easier...