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


In reply to Re: Automatically creating incremental file names by richardX
in thread Automatically creating incremental file names by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.