Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Date in filename

by Anonymous Monk
on Jul 24, 2001 at 23:45 UTC ( [id://99460] : perlquestion . print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Can anyone tell me how to put the date automatically (meaning not having to type it in) into a filename?

Replies are listed 'Best First'.
Re: Date in filename
by Russ (Deacon) on Jul 24, 2001 at 23:58 UTC
    How about POSIX::strftime?
    use POSIX; open FH, '>'.strftime('%Y%m%d', localtime) or die "Nope: $!";

    Russ
    Brainbench 'Most Valuable Professional' for Perl

      Thanks Russ. You rock!
Re: Date in filename
by lhoward (Vicar) on Jul 24, 2001 at 23:59 UTC
    One method of many.....
    use POSIX; my $filename=POSIX::strftime("%Y%m%d",localtime(time()))."_foo.dat"; open F,">$filename" or die "error opening $filename : $!"; ...
      Thanks lhoward. Most appreciated!
Re: Date in filename
by dsb (Chaplain) on Jul 25, 2001 at 00:41 UTC
    If you are worried about uniqueness in the filename, you are probably better of using the UNIX timestamp.
    $file = time() . "whatever.ext";
    The time function returns the UNIX time in seconds since the epoch. Using this method also prevents spaces from being in the filename that would be there if you used localtime.

    Might want to take a look at perlfunc.

    Amel - f.k.a. - kel

      If you are really searching for a uniqe filename, you should quite propably add $$ (the process-ID) to it, to be on the save side. So you can have multiple programs running at the same time that do not interfere:
      $file = time()."-$$.tmp";
      HTH!
      --
      use signature; signature(" So long\nAlfie");
      Thanks Amel. This is actually better than what I wanted. I'm gonna use it!