Temporary Files And Directories in Perl

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

use strict;
use warnings;
use File::Temp qw/ tempfile tempdir /;
use File::Spec;

sub check {
    my ($error) = @_;
    die $error if $error;
}

# The easiest way to create a temporary file is by
# using File::Temp's tempfile function. It creates a file *and*
# opens it for reading and writing. We provide an empty list
# as the first argument, so tempfile will create the file
# in the default location for our OS.
my ($fh, $filename) = tempfile("sampleXXXXX", SUFFIX => '.txt');
print "Temp file name: $filename\n";

# Clean up the file after we're done. The OS is
# likely to clean up temporary files by itself after
# some time, but it's good practice to do this
# explicitly.
END { unlink $filename or warn "Could not unlink $filename: $!" }

# We can write some data to the file.
print $fh pack('C*', 1, 2, 3, 4);

# If we intend to create many temporary files, we may
# prefer to create a temporary *directory*.
# File::Temp's tempdir function returns a directory name.
my $dname = tempdir("sampledirXXXXX", CLEANUP => 1);
print "Temp dir name: $dname\n";

# Now we can synthesize temporary file names by
# prefixing them with our temporary directory.
my $fname = File::Spec->catfile($dname, "file1");
open my $file, '>', $fname or die "Could not open $fname: $!";
print $file pack('C*', 1, 2);
close $file;

To run the program, save it as temporary_files_and_directories.pl and use perl:

$ perl temporary_files_and_directories.pl
Temp file name: /tmp/sampleабвгд.txt
Temp dir name: /tmp/sampledirеёжзи

In this Perl version:

  1. We use the File::Temp module to create temporary files and directories.
  2. The tempfile function is used instead of os.CreateTemp. It returns a filehandle and the name of the created file.
  3. We use END block for cleanup instead of defer. This ensures the temporary file is deleted when the script exits.
  4. The tempdir function is used to create a temporary directory.
  5. We use File::Spec->catfile to join directory and file names in a platform-independent way.
  6. Error handling is done using die instead of panic.
  7. File writing is done using Perl’s built-in print function and pack to create binary data.

Note that Perl’s temporary file and directory creation functions automatically ensure unique names, so we don’t need to worry about conflicts in concurrent operations.