cpan beginner

How to use File::Temp to create temporary file in Perl?

Question

How to use File::Temp to create temporary file in Perl?

The File::Temp module in Perl provides a convenient and secure way to create temporary files and directories. It ensures that the temporary files are created with unique names, securely, and automatically cleaned up when no longer needed. This is safer than manually creating temporary files, as it helps avoid filename collisions and potential security issues.

How to Create a Temporary File Using File::Temp

To create a temporary file, you typically use the File::Temp->new() method or the tempfile() function. Both generate a filehandle to the temporary file, which you can then read from or write to just like any regular filehandle.

Here is what happens under the hood:

  • The temporary filename is generated securely to avoid clashes or guessing.
  • The file is opened with appropriate permissions (usually 0600).
  • When the File::Temp object is destroyed (goes out of scope), the file is automatically deleted, unless you specify otherwise.

Useful Features of File::Temp

  • Automatic cleanup: Files are removed when the filehandle or File::Temp object is closed or destroyed.
  • Use of filehandles: You get a Perl filehandle to read/write to the temp file.
  • Custom templates: You can specify filename templates.
  • Cross-platform: Works on Windows and Unix-like systems.

Perl Version and Core Module

File::Temp is a core module included in Perl since version 5.6, so no extra installation is needed. It has improved features since 5.10+ with some additional options.

Example: Creating and Writing to a Temporary File

use strict;
use warnings;
use File::Temp;

# Create a new temporary file
my $temp_fh = File::Temp->new(
    TEMPLATE => 'tempfileXXXX',  # filename template: X replaced with random chars
    SUFFIX   => '.txt',          # optional suffix
    UNLINK   => 1,               # automatically delete file on close or destruction
);

# Fetch the temporary filename just for demonstration
my $temp_file = $temp_fh->filename;

print "Temporary file created: $temp_file\n";

# Write some text to the temporary file
print $temp_fh "Hello, this is a temporary file.\n";
print $temp_fh "Perl File::Temp makes temp files easy!\n";

# Flush output to ensure contents are written
$temp_fh->flush;

# Seek back to read the contents (optional)
seek($temp_fh, 0, 0);

# Read and print the file contents to STDOUT to verify
my @lines = <$temp_fh>;
print "Contents of temp file:\n", @lines;

# When $temp_fh goes out of scope, the temporary file will be removed automatically
# because UNLINK => 1 was set (default behavior)

Explanation of Key Points

  • File::Temp->new() returns a filehandle tied to the temporary file.
  • You can print to the filehandle normally.
  • Using TEMPLATE lets you define a pattern with X characters replaced by random values.
  • UNLINK => 1 (default) means the file is deleted automatically; use 0 to keep it.
  • flush() writes buffered output to disk; not always needed but good practice.
  • flush and seek enable reading back the content from the filehandle.
  • Using the object-oriented interface is cleaner and recommended over the older procedural function tempfile().

Common Pitfalls

  • Not closing or letting the filehandle go out of scope means the file may not get deleted immediately.
  • On Windows, files cannot be reopened for reading if opened with certain modes, so using the filehandle for both writing and reading requires binmode or careful handling.
  • If you want the temp file to persist after program exit, set UNLINK => 0, but you must manually clean it later.

Overall, File::Temp is the go-to solution for temporary files in Perl for both beginners and advanced users, thanks to its safety and convenience.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 51ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Temporary file created: tempfiledrFq.txt
Contents of temp file:
Hello, this is a temporary file.
Perl File::Temp makes temp files easy!
STDERR
(empty)

Was this helpful?

Related Questions