Just a little snippet to return sequential file names of the form aaaa, aaab, aaac, etc. When a character gets to 'z', it resets again to 'a' and increments the next character to the left by one. If it runs out of names, it switches to the POSIX tmpnam() function as a last resort. You can use any number of characters, but should not need too many: X characters will generate 26^X combinations before resorting to tmpnam(). The second argument is the direction, anything but a minus number means ascending. If you don't care about clobbering existing files, just throw in a third argument. Sample usage:

my $filename = "xyz"; for (1..10) { print qq[Filename is "$filename"\n]; $filename = &newname($filename,1); }

I recommended that you keep track of the names generated unless you are overwriting so that you can be aware of any "holes" in the sequence.

Update: Made it ascending and descending based on tye's challenge^H^H^H^H^H^H^H^H^Hcomment, and that fact that $filename-- fails miserably to act like $filename++ does. :)

sub newname() { my $filename = shift || "aaaa"; my $sign = shift || 1; my $overwrite = shift; { my $x = 1; 1 while substr($filename,-$x++,1) eq ($sign<1 ? "a":"z"); if (--$x > length $filename) { $filename = tmpnam(); } else { substr($filename,-$x--,1)=chr(ord(substr($filename,-$x,1))+$sign +); substr($filename,-$x--,1)=($sign<1 ? "z":"a") while $x; } redo if !$overwrite and -e $filename; return $filename; } }

In reply to Sequential names by turnstep

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.