Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Do you know where your variables are?
 
PerlMonks  

Avoiding making a directory that already exists

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

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

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 scain (Curate) on Aug 19, 2001 at 18: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...
Re: Avoiding making a directory that already exists
by VSarkiss (Monsignor) on Aug 19, 2001 at 18:07 UTC
      this is what I needed :) thx
Re: Avoiding making a directory that already exists
by Rudif (Hermit) on Aug 19, 2001 at 19: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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://106039]
Approved by root
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.