use Fcntl; # need constants O_CREAT | O_EXCL | O_RDWR sub get_tempfile { my ( $dir, $prefix, $max_tries ) = @_; $dir ||= '/tmp'; $prefix ||= 'temp'; $max_tries ||= 10; my @CHARS = ( 'A' .. 'Z', 'a' .. 'z', 0 .. 9, '_' ); ui_system_error( "$dir is not a directory" ) unless -d $dir; ui_system_error( "$dir is not writable" ) unless -w $dir; $dir =~ s!/$!!; my $fh; for ( 0 .. $max_tries ) { my $name = sprintf "$prefix-%d-", time(); $name .= $CHARS[ int( rand( $#CHARS ) ) ] for 1..10; my $path = "$dir/$name"; return ($fh, $name) if sysopen($fh, $path, O_CREAT | O_EXCL | O_RDWR, 0600); } ui_system_error( "Could not create unique filename after $max_tries" ); }