cpan beginner

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

  • touch creates a zero-length file if it doesn’t already exist.
  • If the file exists, touch updates its modification timestamp to the current time.
  • Path::Tiny methods use the $path->method syntax, where $path is a Path::Tiny object representing the file/directory.
  • Since touch operates on a path object, you first create a Path::Tiny object representing the target file.
  • Path::Tiny is 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 a Path::Tiny object for the filename.
  • $file->touch creates the file or updates its mtime.
  • $file->stringify returns the string path, useful for printing.

Common Pitfalls

  • Make sure the directory you want to create the file in exists, otherwise touch will fail with a permissions or directory not found error.
  • touch only updates modification/access times; it does not create parent directories automatically.
  • If you want to write actual content to the file, use the spew or open methods rather than touch.
  • Path::Tiny is 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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
File example.txt has been touched/created.
STDERR
(empty)

Was this helpful?

Related Questions