Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Automatically creating incremental file names

by richardX (Pilgrim)
on May 28, 2003 at 02:45 UTC ( [id://261191]=note: print w/replies, xml ) Need Help??


in reply to Automatically creating incremental file names

Here is a snippet from a program that I use daily that checks for a duplicate file name in the out bucket and renames the in bucket filename if it already exists.

#check for dup name if (-e "$fn_out/$fname") { print "Dup:: $fn_out/$fname\n"; my ($name, $ext) = ($fname =~ /^(.+?)(\.[^.]+)?$/); $ext = "" unless $ext; my $i = 0; while (-e "$fn_out/$fname_new") { ++ $i; $fname_new = sprintf "$name-%02d$ext", $i; } my $uni = $fname_new; print "New:: $fn_out/$uni\n\n"; rename ("$fn_in/$fname", "$fn_out/$uni"); }else{ rename ("$fn_in/$fname", "$fn_out/$fname"); print "Dest:: $fn_out/$fname\n\n"; }

$fn_in is the directory for the in bucket of file names. $fn_out is the directory for the out bucket of file names

The critical line is a self incrementing line until it finds a file name that does not exist in the out bucket.

$fname_new = sprintf "$name-%02d$ext", $i;

The format of the file name will be FILENAME-NN.EXT where NN is an incrementing number. You can easily customize this to your likes.

I like using this solution because it works on all platorms and does not require any overhead or modules.

Richard

There are three types of people in this world, those that can count and those that cannot. Anon

Replies are listed 'Best First'.
Re: Re: Automatically creating incremental file names
by graff (Chancellor) on May 28, 2003 at 07:01 UTC
    Do you use this approach in a CGI script that is supposed to create files and not over-write/re-use existing file names (as the OP wants to do)?

    If so, the first "customization" that would be needed is something like a separate semaphore file, to be locked before doing the "if (-e ...)" test, and released after leaving whichever block is executed as a result of that test. Otherwise, two competing processes on the same web server could still collide on the same file name.

    (Another customization I'd want is to indent the code properly. But personally, I think the initial reply in this thread, suggesting a SHA1 signature as the file name, has the most merit.)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://261191]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-03-28 12:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found