How to get a unique filename in perl
I want to create in a directory ma开发者_StackOverflowny small files with unique names from many processes. Theoretically filenames may be the same, so how do I account for that? What module I should use for this purpose? Files should be persist.
You probably want to use File::Temp
for that.
($fh, $filename) = tempfile($template, DIR => $your_dir, UNLINK => 0);
The package to use would be File::Temp.
Append a timestamp to each file, up to the millisecond:
#!/usr/local/bin/perl
use Time::HiRes qw(gettimeofday);
my $timestamp = int (gettimeofday * 1000);
print STDOUT "timestamp = $timestamp\n";
exit;
Output:
timestamp = 1227593060768
Without any modules you could use something like this: time() . "_" . rand()
$$ contains the process id of the running perl program. Therefore it can be used in file names to make them unique at least between instances of the running process.
精彩评论