This sub ensures that a unique filename is available for purposes such as generating a backup file before performing some sort of file maipulation, or for when a unique temporary file is required
sub get_unique_filename { my ( $name, $max_tries ) = @_; return if not -e $name; $name =~ s/(\.[^\.]+)$//; my $ext = $1 ? $1 : ''; my $tries = 1; my $max_tries ||= 100; while ( -e $name.$tries.$ext ) { $tries++; die "Could not make a unique filename for $name$ext\n" if $tri +es > $max_tries; } return $name.$tries.$ext; }

Replies are listed 'Best First'.
Re (tilly) 1: Unique filename
by tilly (Archbishop) on May 22, 2001 at 21:33 UTC
    I recommend File::Temp for a better version of this wheel.
(tye)Re: Unique filename
by tye (Sage) on May 22, 2001 at 20:50 UTC

    This generates a classic race condition. To avoid that you need to have this function open the file with the O_EXCL flag specified and then retry with the next free file name if that fails.

            - tye (but my friends call me "Tye")

      Hmm, I have to concur. Just wrapped the code around the regex without sufficient thought. Given that its function it should really pass back a locked filehandle for writing. On the to do list

      $\=' '; sub AUTOLOAD{@_=caller();print shift} package Back;&::; package To;&::; package The;&::; package Drawing;&::; package Board;&::;
      tachyon
Re: Unique filename
by shelob101 (Sexton) on May 27, 2001 at 00:41 UTC
    here's what I use, there may be "race condition" issues with it but I've had it in production for a couple of years with no problems:
    $filename="/data/base_file."; $x=0; $x++ while (-e $filename.$x); $realfile=$filename.$x;
Re: Unique filename
by John M. Dlugosz (Monsignor) on Jun 07, 2001 at 23:54 UTC
    A simple way to make a unique filename is to to use a GUID (aka UUID). No races, no checking needed!