#!/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('./tmp_*.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; }