Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Creating new folders

by kyle (Abbot)
on Feb 03, 2008 at 04:26 UTC ( #665799=note: print w/replies, xml ) Need Help??


in reply to Creating new folders

My usual way to ensure that a directory exists is:

my $dir = ...; if ( ! -d $dir && ! mkdir $dir ) { die "Can't mkdir '$dir': $!"; }

This reads fairly naturally to me as "if it's not there, and I can't make it, die with a good error message." If you're concerned that the directory above the one you want might not be there (and therefore would block you trying to create the one you want), look at mkpath in File::Path.

For your particular case, where you want to do this with multiple directories, I'd probably put the directories in a list and then loop over that.

my @wanted_directories = ( "e:/web/public_html/eagle_f91/ffinfo/protected/images/$Game", "e:/web/public_html/eagle_f91/ffinfo/protected/images/$Game/$S +ubSet", "e:/web/public_html/eagle_f91/ffinfo/protected/images/$Game/$S +ubSet/thmb" ); foreach my $dir ( @wanted_directories ) { if ( ! -d $dir && ! mkdir $dir ) { die "Can't mkdir '$dir': $!"; } }

Replies are listed 'Best First'.
Re^2: Creating new folders
by Anonymous Monk on Feb 03, 2008 at 10:57 UTC
    In general I try very hard to avoid the race condition that come from assuming the result of a filetest operator remains valid. In this case it is possible that something creates the directory between the moment of the -d and the mkdir and that's a case I'd prefer to work instead of fail. In many real cases this is impossible or not an issue of course, but I still prefer my code to be able to handle such cases. So normally I'd write:
    if (!mkdir($dir)) { my $err = $!; die "Could not create $dir: $err" unless -d $dir; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://665799]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (2)
As of 2021-10-23 01:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (86 votes). Check out past polls.

    Notices?