Title here
Summary here
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:
File::Temp
module to create temporary files and directories.tempfile
function is used instead of os.CreateTemp
. It returns a filehandle and the name of the created file.END
block for cleanup instead of defer
. This ensures the temporary file is deleted when the script exits.tempdir
function is used to create a temporary directory.File::Spec->catfile
to join directory and file names in a platform-independent way.die
instead of panic
.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.