How to use Path::Tiny touch to create empty file in Perl?
Question
How to use Path::Tiny touch to create empty file in Perl?
How to Use Path::Tiny touch to Create an Empty File in Perl
Path::Tiny is a lightweight, modern Perl module for working with file paths and files in an easy and robust way. One useful method it offers is touch, which mimics the UNIX touch command. It can create an empty file if the file does not exist, or update the modification time if the file already exists.
This makes touch very handy for creating empty files safely, with minimal lines of code.
Key Points About touch in Path::Tiny
touchcreates a zero-length file if it doesn’t already exist.- If the file exists,
touchupdates its modification timestamp to the current time. Path::Tinymethods use the$path->methodsyntax, where$pathis aPath::Tinyobject representing the file/directory.- Since
touchoperates on a path object, you first create aPath::Tinyobject representing the target file. Path::Tinyis part of the core Perl distribution starting with Perl 5.26 (with some embedded subset), otherwise you install it from CPAN.
Basic Example: Creating an Empty File with touch
The following simple script demonstrates how to create an empty file named example.txt. If the file exists, its modification time is updated.
use strict;
use warnings;
use Path::Tiny;
# Create a Path::Tiny object for the target file
my $file = path("example.txt");
# Create the file if it doesn't exist, or update the mtime if it does
$file->touch;
print "File ", $file->stringify, " has been touched/created.\n";
Explanation
path("example.txt")creates aPath::Tinyobject for the filename.$file->touchcreates the file or updates its mtime.$file->stringifyreturns the string path, useful for printing.
Common Pitfalls
- Make sure the directory you want to create the file in exists, otherwise
touchwill fail with a permissions or directory not found error. touchonly updates modification/access times; it does not create parent directories automatically.- If you want to write actual content to the file, use the
speworopenmethods rather thantouch. Path::Tinyis case-sensitive on case-sensitive file systems (Linux, macOS default), so ensure your file names are correct.
Summary
Path::Tiny’s touch method is a simple and effective way for beginners to create an empty file or update an existing file’s timestamp in Perl. It abstracts away lower-level file handling, providing readable, maintainable code.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 50ms
File example.txt has been touched/created.
(empty)Was this helpful?
Related Questions
- How to use File::Slurp to read entire file into variable in Perl?
- How to get file modification time with Path::Tiny in Perl?
- How to use List::Util reduce for custom aggregation in Perl?
- How to compare two DateTime objects in Perl?
- How to use DateTime::Duration for time periods in Perl?
- How to decode Base64 string in Perl using MIME::Base64?