in reply to Checking for Directories

I just noticed your purpose. I recommend that if you want to create a directory if it's missing, just go ahead and call the mkdir operator every time the program runs. The mkdir may fail if the directory is there, but who cares? It's not like there's any penalty for setting $!. :-)

    -- Chip Salzenberg, Free-Floating Agent of Chaos

Replies are listed 'Best First'.
RE: Don't Check for Directories
by tye (Sage) on Jul 29, 2000 at 00:39 UTC

    Ah, but the sticky bit there is that you want to ignore a failure due to "directory already exists" and not ignore any other reasons for failure, including "file already exists". Before Errno.pm, this was tricky. Now it isn't so bad except that "file already exists" and "directory already exists" put the same value in $!.

    So I think the easiest robust solution is still to only create the directory if it doesn't already exists.

      Well, I still don't see the point in checking ... after all, what's the next thing you'll do? That's right, create a file in the directory ... and whatever the error is, you can report it.

      Besides, why introduce a race condition without having to?

          -- Chip Salzenberg, Free-Floating Agent of Chaos

        You can report the failure, but not the reason (the file creation will fail for "no such directory" but we won't know why the directory creation failed). I've worked too long in "Support"; I hate programs that fail and give no hint as to why. Or are you suggesting we cache $! after the mkdir and report it if the next file creation failed??

        Good point on the race condition.

        I don't like the follow-up suggestion of using system("mkdir -p"), since you lose portability. But using use File::Path qw(mkpath) makes sense, especially since it is smart enough to remove the most common race condition.

        The improvement is to use mkdir -p. This will create the directory, including parents, but give no error if it exists already. I use this in some scripts a lot. It works. It's even mentioned in the man page.

        -- Kirby

        Tuxtops: Laptops with Linux!