12

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 I need to check if they exist first before creating them.

How can I do 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?

0

4 Answers 4

19

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

I kind of agree, but figured they are a good package deal to know when trying to do this kind of stuff.
14

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;
}

2 Comments

Checking $@ is unreliable. Use eval{mkpath($dir); 1} or do { warn "badness\n" }. See search.cpan.org/dist/Acme-ExceptionEater/lib/Acme/… for an example of why checking $@ is bad.
As of v2.09(2013-01) it appears that it is now make_path
7

Remember the directory's -d existence doesn't mean -w writable. But assuming you're in a personal area the mkdir($dir) unless(-d $dir) would work fine.

Comments

3

Perl has a built-in function mkdir

Take a look at perldoc perlfunc or the mkdir program from Perl Power Tools.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.