views:

1389

answers:

4

Currently, my Perl output is hard-coded to dump into the following UNIX directory:

my $stat_dir = "/home/courses/".**NEED DIR VAR HERE**;

The filename is built as such:

$stat_file = $stat_dir . "/".$sess.substr($yr, 2, 2)."_COURSES.csv";

I need a similar approach to building UNIX directories, but need to check if they exist first before creating them.

BONUS EXTRA CREDIT WIN:
Auto-numbering (revisions) of the $stat_file so that when these files get pumped into the same directory, they do not overwrite or append to existing files in the directory. (I don't know if this question has been fielded yet on S.O. - sorry if its a re-post)

+7  A: 

Use the -d operator and File::Path.

eval { mkpath($dir) };
if ($@) {
  print "Couldn't create $dir: $@";
}

mkpath has an advantage (over mkdir) that it can create trees of arbitrary depth.

And use -e to check file exists

my $fileSuffix = 0;
while (-e $filename) {
    $filename = $filePrefix . ++$fileSuffix . $fileExtension;
}
Ed Guiness
Checking $@ is unreliable. Use eval{mkpath($dir); 1} or do { warn "badness\n" }. See http://search.cpan.org/dist/Acme-ExceptionEater/lib/Acme/ExceptionEater.pm for an example of why checking $@ is bad.
daotoad
+3  A: 

Erm... mkdir $stat_dir unless -d $stat_dir?

It really doesn't seem like a good idea to embed 'extra' questions like that.

chaos
I kind of agree, but figured they are a good package deal to know when trying to do this kind of stuff.
CheeseConQueso
+2  A: 

Perl has a built-in funtion 'mkdir'

take a look at perldoc perlfunc or the mkdir script from Perl Power Tools.

I believe it is safe to create a directory that already exists, take a look at the docs

MGoDave
+2  A: 

Remember the directories -d existence doesnt mean -w writeable. But assuming your in a personal area the mkdir($dir) unless(-d $dir) would work fine.

hpavc