Code to generate random file names

K

Kev

I'm downloading files from the internet and need some code that would use
the time to name the files. Could someone who may have this code share it?

Thanks.

Kev
 
T

Tony Curtis

I'm downloading files from the internet and need some code
that would use the time to name the files. Could someone who
may have this code share it?

That's not really the same as "random", is it?

There are lots of ways of doing this, here's the way I tend to
write it:

use POSIX qw(strftime);
my $fname = strftime('download/%H.%M.%S', localtime);

or whatever path/format you really want. "perldoc POSIX" for
more.

Of course, just using the time-since-epoch might be what you
want, in which case, just interpolate the value of time().

hth
t
 
T

Tad McClellan

Kev said:
need some code that would use
the time to name the files


What does that have to do with what you put in your Subject header?


my $filename = time;
 
M

Matthew Braid

Kev said:
I'm downloading files from the internet and need some code that would use
the time to name the files. Could someone who may have this code share it?

Thanks.

Kev

If you absolutely must have the time in there somewhere, you can do
something like: (UNTESTED!)

----- START CODE -----
use Fcntl qw/O_WRONLY O_CREAT O_EXCL/;
use IO::File;

my $dir = '/tmp/'; # Or wherever
my $perms = 0640; # You may want to change this
my @time = localtime;
$time[4]++;
$time[5] += 1900;
my $fh = IO::File->new;
my $fname;
while (1) {
my $rnd = int(rand(1e14)); # sprintf can't handle %014d
$rnd = ('0' x (14 - length($rnd))) . $rnd;
$fname = sprintf("$dir%04d%02d%02d%02d%02d%02d.$rnd",
reverse(@time[0..5]));
last if $fh->open($fname, O_CREAT|O_EXCL|O_WRONLY, $perms);
next if $! =~ /File exists/;
die "Failed to create file - $!";
}
print "Created a new file named $fname\n";
$fh->close; # Obviously you'd do something with $fh first
----- END CODE -----

This would give you a filename (and an open filehandle, which is even
more useful) of something like /tmp/20031107165921.00197626901823.

All it expects is that you already know where the temp directory is but
I'm guessing there's a handy package out there for giving you that too.

MB
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top