From 16394a69320526f76d6352cbf28d1f966c7cc2d7 Mon Sep 17 00:00:00 2001 From: Jarkko Hietaniemi Date: Mon, 6 Aug 2001 13:24:28 +0000 Subject: [PATCH] Advertise File::Temp, don't advertise POSIX::tmpnam(). p4raw-id: //depot/perl@11596 --- pod/perlfaq5.pod | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/pod/perlfaq5.pod b/pod/perlfaq5.pod index 5061f69..daa8348 100644 --- a/pod/perlfaq5.pod +++ b/pod/perlfaq5.pod @@ -174,32 +174,25 @@ This assumes no funny games with newline translations. =head2 How do I make a temporary file name? -Use the C class method from the IO::File module to get a -filehandle opened for reading and writing. Use it if you don't -need to know the file's name: +Use the File::Temp module, see L for more information. - use IO::File; - $fh = IO::File->new_tmpfile() - or die "Unable to make new temporary file: $!"; - -If you do need to know the file's name, you can use the C -function from the POSIX module to get a filename that you then open -yourself: + use File::Temp qw/ tempfile tempdir /; + $dir = tempdir( CLEANUP => 1 ); + ($fh, $filename) = tempfile( DIR => $dir ); - use Fcntl; - use POSIX qw(tmpnam); + # or if you don't need to know the filename - # try new temporary filenames until we get one that didn't already - # exist; the check should be unnecessary, but you can't be too careful - do { $name = tmpnam() } - until sysopen(FH, $name, O_RDWR|O_CREAT|O_EXCL); + $fh = tempfile( DIR => $dir ); - # install atexit-style handler so that when we exit or die, - # we automatically delete this temporary file - END { unlink($name) or die "Couldn't unlink $name : $!" } +The File::Temp has been a standard module since Perl 5.6.1. If you +don't have a modern enough Perl installed, use the C +class method from the IO::File module to get a filehandle opened for +reading and writing. Use it if you don't need to know the file's name: - # now go on to use the file ... + use IO::File; + $fh = IO::File->new_tmpfile() + or die "Unable to make new temporary file: $!"; If you're committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many @@ -207,7 +200,7 @@ temporary files in one process, use a counter: BEGIN { use Fcntl; - my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMP} || $ENV{TEMP}; + my $temp_dir = -d '/tmp' ? '/tmp' : $ENV{TMPDIR} || $ENV{TEMP}; my $base_name = sprintf("%s/%d-%d-0000", $temp_dir, $$, time()); sub temp_file { local *FH; -- 2.7.4