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

Hey,

The documentation states: "The make_path function creates the given directories if they don't exists before.

Still,

make_path $path or die "Couldn't create tmp dir: $!\n";
keeps on giving me plenty of "Couldn't create tmp dir: File exists".

I even tried surrounding the whole thing with if (!-e $path) { ... }, but of course that doesn't help in case of a race condition, since several instances of the script are forked off in my code. But shouldn't make_path deal with this by default?

I need to sit down and work through the "Error handling" part because I don't understand it yet, but will that help at all in my case, with several instances of the script all trying to create the directory before writing to it?

Replies are listed 'Best First'.
Re: Problem with make_path in File::Path
by MidLifeXis (Monsignor) on Jul 20, 2012 at 16:24 UTC

    Let's assume the simplest case - you run the make_path call with the same parameters twice in a row. Assume that the first time the $path does not exist. The second time, since the $path already exists, the function returns a value of (), which is false, triggering the die.

    See the documentation for File::Path for more details.

    Update: Change the return value from 0 to ()

    --MidLifeXis

      ***argh***

      I'll admit it is implicit in "...in scalar context (the function returns) the number of directories created", but there is no way I would have got it without your help! Reading between the lines that way presupposes much more experience with Perl.

Re: Problem with make_path in File::Path
by toolic (Bishop) on Jul 20, 2012 at 17:14 UTC
    Keep reading the doc for File::Path:
    The function returns the list of directories actually created during the call; in scalar context the number of directories created.
    If make_path makes a directory which didn't already exist, it returns 1, which means the die is not executed.

    If make_path does not need to make a directory because it already exists, it returns undef, which means the die is executed. But, you do not want it to die because you are emulating 'mkdir -p'.

    Just use:

    make_path $path;

    Or, use error => \$err as specified in the docs.