CheeseConQueso CheeseConQueso - 5 months ago 12x
Perl Question

How can I create a directory if one doesn't exist using Perl?

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.

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)


Use the -d operator and File::Path.

use File::Path qw(make_path);
eval { make_path($dir) };
if ($@) {
  print "Couldn't create $dir: $@";

make_path has an advantage over mkdir in 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;