Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

create folder if doesn't already exist...

Status
Not open for further replies.

spewn

Programmer
May 7, 2001
1,034
i need to create a folder named fx on my server, automatically, provided it doesn't exist.

i have this code:

Code:
use Cwd;

$tn = 'fx';

$path = getcwd();
$path =~ s|\|/|g;
$dir = $tn;
$path.=$dir;
mkdir($path);

i keep getting an error, tho.

any help?

- g

 
What error? Print $path and $!

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
i don't understand what you mean...although i'm appreciating the help!

- g
 
What error? Print $path and $!
roughly translates into
Code:
mkdir($path) || print "Tried to make path >$path< but getting error >$!<\n";
The idea is to allow you to cross examine if you're asking for a valid directory name (I know you're using getcwd() but it's a beta-testing thing)
Also, once you get the error, $! should give you an idea what the OS is complaining about (The directory may already exist .... don't know off the top of my head if mkdir errors if the directory exists)
A couple of thoughts:
- I've had fairly good success without doing the "s|\|/|g" conversion. About the only time it comes into play for me is if I'm trying to submit a system call. The interpreter is otherwise keeping track of it for me. As such, I tend to stick with using "/" for directory separation.
- While I'm presuming that you've supplied a code fragment above and your production code is more robust, I'll toss in a comment to take care in the way you use mkdir(). You may end up dozens (if not thousands) of 'fx' directories under everything (C:/tmp/fx/fx/fx/fx/fx .. and one infinite loop later you're out of disk space.)
 
also you can use th -e file test to see if something already exists.

if (! -e '/path/to/dir') {
mkdir('/path/to/dir') or die "Can't create /path/to/dir:$!\n";
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[noevil]
Travis - Those who say it cannot be done are usually interrupted by someone else doing it; Give the wrong symptoms, get the wrong solutions;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top