in reply to Re: get new item name
in thread get new item name
(Note that this philosophy with regard to order of actions to prevent race conditions with temporary files is based upon discussions within the comp.lang.perl.moderated newsgroup thread here and a BUGTRAQ post from Tom Christiansen here)
#!/usr/bin/perl use Fcntl; use strict; my $fname = nextunique( 'aaa', [ map { m/tmp_(\D+).txt$/ } glob('./tmp +_*.txt') ] ); do { $fname = nextunique( $fname, [ map { m/tmp_(\D+).txt$/ } glob('./t +mp_*.txt') ] ); } until open (FH, $fname, O_RDWR|O_CREAT|O_EXCL, 0666); # code follows close FH; sub nextunique { my ($test_item, $item_list) = @_; exit 1 unless UNIVERSAL::isa( $item_list, 'ARRAY' ); foreach ( @{ $item_list } ) { if ( $_ eq $test_item ) { ++$test_item; last; } } return $test_item; }
You will also note that I have removed the while loop within the nextunique subroutine, thereby minimising the chance of an infinite loop should the element $new_item not exist within @{ $item_list }. A more defensive approach to programming? Maybe, maybe not ...
perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'
|
|---|