http://qs1969.pair.com?node_id=139992

You are running a test and want to create a bunch of temporary files in a directory, or tables in a database with unique but not random names, and you want some minimal protection against race conditions. You might use something like nextuniq() for the files:

my $files_like = time; my @existing = map {m/tmp_(\d+)$/} glob('./tmp_*'); my $next_file = nextuniq($files_like,\@existing); open TEMP,">./tmp_$next_file" or die; # do something close TEMP;

or use it like this for the tables:
my $tables_like = 'test001'; my $tables = [$dbh->tables()]; my $test_table = nextuniq($tables_like,$tables); my $sth = $dbh->prepare("CREATE TABLE $test_table (". "RowID INTEGER(3) PRIMARY KEY,". "DrawingNo VARCHAR(6) NULL ,") or die $dbh->errstr; $sth->execute; # do something $dbh->do("DROP TABLE $test_table");

see rob_au's comments for making something like this more safe - the do{}until, is especially nice. (But, his version of the nextunique() procedure won't work the same and I see no advantage).
mkmcconn

sub nextuniq{ my ($test_item,$item_list) = @_; my $new_item; my $found = 1; if (! UNIVERSAL::isa( $item_list, "ARRAY" )){ require Carp; Carp::croak( "Arg 2 must be an array reference\n"); } while ($found) { $found = 0; foreach $new_item (@$item_list) { if ($new_item eq $test_item) { $test_item++; $found = 1; } } } $new_item = $test_item; $new_item; }