Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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

In reply to get new item name by mkmcconn

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-04-19 14:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found