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;
}
}