File Paths in Perl

Here’s the translation of the Go code example to Perl, with explanations in Markdown format suitable for Hugo:

The File::Spec module provides functions to parse and construct file paths in a way that is portable between operating systems; dir/file on Linux vs. dir\file on Windows, for example.

use strict;
use warnings;
use File::Spec;
use File::Basename;

# `catfile` should be used to construct paths in a
# portable way. It takes any number of arguments
# and constructs a hierarchical path from them.
my $p = File::Spec->catfile("dir1", "dir2", "filename");
print "p: $p\n";

# You should always use `catfile` instead of
# concatenating `/`s or `\`s manually. In addition
# to providing portability, `catfile` will also
# normalize paths by removing superfluous separators
# and directory changes.
print File::Spec->catfile("dir1//", "filename") . "\n";
print File::Spec->catfile("dir1/../dir1", "filename") . "\n";

# `dirname` and `basename` can be used to split a path to the
# directory and the file.
print "Dir(p): " . dirname($p) . "\n";
print "Base(p): " . basename($p) . "\n";

# We can check whether a path is absolute.
print File::Spec->file_name_is_absolute("dir/file") ? "true" : "false", "\n";
print File::Spec->file_name_is_absolute("/dir/file") ? "true" : "false", "\n";

my $filename = "config.json";

# Some file names have extensions following a dot. We
# can split the extension out of such names with `fileparse`.
my ($name, $dir, $ext) = fileparse($filename, qr/\.[^.]*/);
print "$ext\n";

# To find the file's name with the extension removed,
# we can use the $name returned by `fileparse`.
print "$name\n";

# `abs2rel` finds a relative path between a *base* and a
# *target*. It returns undef if the target cannot
# be made relative to base.
my $rel = File::Spec->abs2rel("a/b/t/file", "a/b");
print defined $rel ? $rel : "undef", "\n";

$rel = File::Spec->abs2rel("a/c/t/file", "a/b");
print defined $rel ? $rel : "undef", "\n";

To run the program, save the code in a file (e.g., file_paths.pl) and use the perl command:

$ perl file_paths.pl
p: dir1/dir2/filename
dir1/filename
dir1/filename
Dir(p): dir1/dir2
Base(p): filename
false
true
.json
config
t/file
../c/t/file

This Perl script demonstrates various file path operations using the File::Spec and File::Basename modules, which provide portable file path manipulation functions. The script shows how to join path components, split paths into directory and filename parts, check for absolute paths, work with file extensions, and find relative paths between two locations.