# Finds a new file name using suggested name or prefix, # creates an empty file with this name, and returns it. # Useful to write a file without overwriting something. # Prevents race conditions with mkdir filename.d. # Finds a new file name, creates an empty file with this name, and # returns it. Prevents race conditions with mkdir filename.d. # The input parameter filename is used if the file does not exist, # otherwise it is used as prefix, like filename.cnt, with cnt=0,1,... # sub get_new_filename { my $filename = shift; my $cnt=-1; my $f=$filename; while (-e $f || !mkdir("$f.d",0700)) { $cnt++; $f = "$filename.$cnt"; } local *F; open(F,">$f") or die; close(F); rmdir("$f.d"); return $f; } # a similar function with a time stamp sub get_new_filenameT { my $filename = shift; use POSIX; $filename.=strftime("%Y-%m-%d-%T", localtime(time)); my $cnt=-1; my $f=$filename; while (-e $f || !mkdir("$f.d",0700)) { $cnt++; $f = "$filename.$cnt"; } local *F; open(F,">$f") or die; close(F); rmdir("$f.d"); return $f; }