1. Perl
  2. Module
  3. here

File::Temp - Create a temporary file

You can use File::Temp to create temporary files and temporary directories . You can create temporary files (or temporary directories) in a secure way regardless of the OS.

# Loading modules and importing functions
use File::Temp qw/tempfile tempdir/;

Use the tempfile function to create a temporary file. The return value is the file handle of the temporary file in the scalar context and the file handle and filename of the temporary file in the list context.

# Create temporary file
$fh = tempfile;
($fh, $filename) = tempfile;

Use the tempdir function to create a temporary directory.

# Create temporary directory
$dir = tempdir;

This is an example that safely overwrites a file using a temporary file. (* 1)

# Safely overwrite files
use File::Temp 'temp file';
use File::Copy 'move';

my $file = shift;

# Get the contents of the file
my $old = get_content ($file);

# Add text
my $new = $old. "Add new text";

# Write new content to file
my ($tempfh, $tempfile) = tempfile;
print $tempfh $new;
close $tempfh;

# Overwrite new file with old file
move $tempfile, $file
  or die "Can't move \" $tempfile\"to \" $file\":$!";

sub get_content {
  my $file = shift;
  
  open my $fh, '<', $file
    or die "Can't open file \" $file\":$!";
  
  my $content = join('', <$fh>);
  
  close $fh;
  
  return $content;
}

(Reference) File::Copy

tempfile options

You can specify options as arguments to tempfile.

# tempfile options
tempfile (DIR =>'somedir', SUFFIX =>'.dat');
DIR Directory where temporary files are created
SUFFIX Extension added to the end of the temporary file

If DIR is omitted, the directory for creating temporary files is automatically determined. For Unix it is/tmp.

Note

* 1 It is not safe to open a file in read/write mode and write to the read file. This is because if the computer crashes during writing, the data before reading will be corrupted. It is safe to write to a different file than the one you read and then overwrite with that file.

Related Informatrion